• "Everything should be made as simple as possible, but not simpler." - Anonymous (although often attributed to Albert Einstein)
  • Enter your email address to subscribe.

  • Categories

  • Recent Comments

  • RSS Statalist: the Stata forum

  • RSS Stackoverflow [Stata]

  • Google Analytics Stats

    Period:Last 30 Days
    Total Visits:10523

Double loops


Can you loop inside a loop? Yes. Actually, you can have loop inside a loop that is inside another loop that is inside another loop… and so on. For example, try the following:

forvalues i=1/4{
__forvalues j=1/4{
____local sum=i'+j’
____ display i'+j’” = ” `sum’
__}
}

[Note: The lines represent indentation.]

In the example above, each element in i is added, one by one, to each element in j. This will return 16 (4×4) results:

1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
1 + 4 = 5
2 + 1 = 3
2 + 2 = 4
2 + 3 = 5
2 + 4 = 6
3 + 1 = 4
3 + 2 = 5
3 + 3 = 6
3 + 4 = 7
4 + 1 = 5
4 + 2 = 6
4 + 3 = 7
4 + 4 = 8

The double loops, such as the example above, is usually used (but not limited to) as subscripts to identify matrix elements in matrix operations. In this context, each ij-pair corresponds to the element of a matrix in row i, column j.

You can also do the following, which will return 256 results:

forvalues i=1/4{
__forvalues j=1/4{
____forvalues k=1/4{
______forvalues l=1/4{
________display i'j’k'l’
______}
____}
__}
}

[Note: The lines represent indentation.]

Leave a Reply

%d bloggers like this: