6.7 Indexing
Stan arrays, matrices, vectors, and row vectors are all accessed
using the same array-like notation. For instance, if x
is a
variable of type array [] real
(a one-dimensional array of reals)
then x[1]
is the value of the first element of the
array.
Subscripting has higher precedence than any of the arithmetic
operations. For example, alpha * x[1]
is equivalent to
alpha * (x[1])
.
Multiple subscripts may be provided within a single pair of square
brackets. If x
is of type array[,] real
, a two-dimensional
array, then x[2, 501]
is of type real
.
Accessing subarrays
The subscripting operator also returns subarrays of arrays. For
example, if x
is of type array[,,] real
, then x[2]
is of type array[,] real
, and x[2, 3]
is of type
array[] real
. As a result, the expressions x[2, 3]
and
x[2][3]
have the same meaning.
Accessing matrix rows
If Sigma
is a variable of type matrix
, then
Sigma[1]
denotes the first row of Sigma
and has the
type row_vector
.
Mixing array and vector/matrix indexes
Stan supports mixed indexing of arrays and their vector, row vector
or matrix values. For example, if m
is of type
matrix[ , ]
, a two-dimensional array of matrices, then
m[1]
refers to the first row of the array, which is a
one-dimensional array of matrices. More than one index may be used,
so that m[1, 2]
is of type matrix
and denotes the matrix
in the first row and second column of the array. Continuing to add
indices, m[1, 2, 3]
is of type row_vector
and denotes
the third row of the matrix denoted by m[1, 2]
. Finally,
m[1, 2, 3, 4]
is of type real
and denotes the value in the
third row and fourth column of the matrix that is found at the first
row and second column of the array m
.