This is an old version, view current version.

## 5.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,

array[7, 8, 9] real x;
array[7] matrix[8, 9] y;

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

array[M, N] real a;

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.

array[] 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.
Available since 2.0

int num_elements(array[] 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 array[4, 3] real then num_elements(x) is 12, and if y is declared as array[5] matrix[3, 4] y, then size(y) evaluates to 60.
Available since 2.5

int size(array[] 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 array[4, 3] real then size(x) is 4.
Available since 2.0