This is an old version, view current version.

7.6 Foreach loops

A second form of for loops allows iteration over elements of containers. If ys is an expression denoting a container (vector, row vector, matrix, or array) with elements of type T, then the following is a well-formed foreach statement.

for (y in ys) {
  // ... do something with y ...
}

The order in which elements of ys are visited is defined for container types as follows.

  • vector, row_vector: elements visited in order, y is of type double

  • matrix: elements visited in column-major order, y is of type double

  • array[] T: elements visited in order, y is of type T.

Consequently, if ys is a two dimensional array array[,] real, y will be a one-dimensional array of real values (type array[] real). If ’ysis a matrix, thenywill be a real value (typereal`). To loop over all values of a two-dimensional array using foreach statements would require a doubly-nested loop,

array[2, 3] real yss;
for (ys in yss) {
  for (y in ys) {
    // ... do something with y ...
  }
}

whereas a matrix can be looped over in one foreach statement

matrix[2, 3] yss;
for (y in yss) {
   // ... do something with y...
}

In both cases, the loop variable y is of type real. The elements of the matrix are visited in column-major order (e.g.,y[1, 1],y[2, 1],y[1, 2], ...,y[2, 3]), whereas the elements of the two-dimensional array are visited in row-major order (e.g.,y[1, 1],y[1, 2],y[1, 3],y[2, 1], ...,y[2, 3]`).