6.8 Multiple Indexing and Range Indexing

In addition to single integer indexes, as described in the language indexing section, Stan supports multiple indexing. Multiple indexes can be integer arrays of indexes, lower bounds, upper bounds, lower and upper bounds, or simply shorthand for all of the indexes. A complete table of index types is given in the indexing options table.

Indexing Options Table. Types of indexes and examples with one-dimensional containers of size N and an integer array ii of type int[] size K.

index type example value
integer a[11] value of a at index 11
integer array a[ii] a[ii[1]], …, a[ii[K]]
lower bound a[3:] a[3], …, a[N]
upper bound a[:5] a[1], …, a[5]
range a[2:7] a[2], …, a[7]
all a[:] a[1], …, a[N]
all a[] a[1], …, a[N]

Multiple Index Semantics

The fundamental semantic rule for dealing with multiple indexes is the following. If idxs is a multiple index, then it produces an indexable position in the result. To evaluate that index position in the result, the index is first passed to the multiple index, and the resulting index used.

a[idxs, ...][i, ...] = a[idxs[i], ...][...]

On the other hand, if idx is a single index, it reduces the dimensionality of the output, so that

a[idx, ...] = a[idx][...]

The only issue is what happens with matrices and vectors. Vectors work just like arrays. Matrices with multiple row indexes and multiple column indexes produce matrices. Matrices with multiple row indexes and a single column index become (column) vectors. Matrices with a single row index and multiple column indexes become row vectors. The types are summarized in the matrix indexing table.

Matrix Indexing Table. Special rules for reducing matrices based on whether the argument is a single or multiple index. Examples are for a matrix a, with integer single indexes i and j and integer array multiple indexes is and js. The same typing rules apply for all multiple indexes.

example row index column index result type
a[i] single n/a row vector
a[is] multiple n/a matrix
a[i, j] single single real
a[i, js] single multiple row vector
a[is, j] multiple single vector
a[is, js] multiple multiple matrix

Evaluation of matrices with multiple indexes is defined to respect the following distributivity conditions.

m[idxs1, idxs2][i, j] = m[idxs1[i], idxs2[j]]
m[idxs, idx][j] = m[idxs[j], idx]
m[idx, idxs][j] = m[idx, idxs[j]]

Evaluation of arrays of matrices and arrays of vectors or row vectors is defined recursively, beginning with the array dimensions.