4.2 Array Size and Dimension Function
The size of an array or matrix can be obtained using the dims()
function. The dims()
function is defined to take an argument
consisting of any variable with up to 8 array dimensions (and up to 2
additional matrix dimensions) and returns an array of integers with
the dimensions. For example, if two variables are declared as
follows,
real x[7,8,9];
matrix[8,9] y[7];
then calling dims(x)
or dims(y)
returns an integer array of size 3
containing the elements 7, 8, and 9 in that order.
The size()
function extracts the number of elements in an array.
This is just the top-level elements, so if the array is declared as
real a[M,N];
the size of a
is M
.
The function num_elements
, on the other hand, measures all of the
elements, so that the array a
above has \(M \times N\) elements.
The specialized functions rows()
and cols()
should be used to
extract the dimensions of vectors and matrices.
int[]
dims
(T x)
Return an integer array containing the dimensions of x; the type of
the argument T can be any Stan type with up to 8 array dimensions.
int
num_elements
(T[] x)
Return the total number of elements in the array x including all
elements in contained arrays, vectors, and matrices. T can be any
array type. For example, if x
is of type real[4,3]
then
num_elements(x)
is 12, and if y
is declared as matrix[3,4] y[5]
,
then size(y)
evaluates to 60.
int
size
(T[] x)
Return the number of elements in the array x; the type of the array T
can be any type, but the size is just the size of the top level array,
not the total number of elements contained. For example, if x
is of
type real[4,3]
then size(x)
is 4.