 # How to declare and use integer matrices

I’m trying to declare and use a 2-column integer data matrix. Here is example code:

`````` vector ff(row_vector[] X, int[] y) {
int N = size(X);
int k = max(y);    // want max over all rows AND columns
vector[N] out;
for(n in 1 : N) {
int j = y[n, 1];
int m = y[n, 2];
out[n] = 0.;
}
return out;
}

data {
int<lower=1> N;
int<lower=1> p;
int<lower=2> k;
matrix[N, p] X;
int<lower=1,upper=k> y[N,2];
}
``````

I get

``````Too many indexes, expression dimensions=1, indexes found=2
error in 'modelc42957b1a0253_test' at line 7, column 18
``````

What is the correct syntax? And will max(y) work OK to find the maximum over the whole matrix?
Thanks for any help.

Hi Frank,

I believe the issue is with the declaration of input dimensions here:

``````vector ff(row_vector[] X, int[] y)
``````

Here, y is declared as a one-dimensional array of integers, but is then indexed in two dimensions in the function body. If you change the input type to two dimensions:

``````vector ff(row_vector[] X, int[,] y)
``````

That should do it

Thanks very much. For the 2nd question how do you get `int k = max(y)` to work? Do I need to do `max(max(y[,1]),max(y[,2]))` ?

If you don’t mind I have one other question… If I have `vector ff(vector a, row_vector[] X)` I see that I must use `int m = num_elements(a)` to obtain the length of the vector `a`. To get the number of columns of `X` I would have thought that `int p = cols(X)` would have worked, but I get `no matches for cols(row_vector[ ]) ... available signatures for cols .. cols(row_vector)`. Any pointers appreciated.

For the 2nd question how do you get `int k = max(y)` to work? Do I need to do `max(max(y[,1]),max(y[,2]))` ?

Sorry I missed that one. Those reductions (min/max/etc) are only defined over one-dimensional arrays, so in your case, a workaround would be:

``````int k = max(to_array_1d(y))
``````

The `to_array_1d` call will induce a copy, so if you want to maximise performance you could move this to the `transformed data` block.

If you don’t mind I have one other question… If I have `vector ff(vector a, row_vector[] X)` I see that I must use `int m = num_elements(a)` to obtain the length of the vector `a` . To get the number of columns of `X` I would have thought that `int p = cols(X)` would have worked, but I get `no matches for cols(row_vector[ ]) ... available signatures for cols .. cols(row_vector)` . Any pointers appreciated.

Because X is a one-dimensional array of row-vectors (`row_vector[]`), there isn’t a concept of rows/columns of an array to count. As Stan doesn’t (yet) allow ragged arrays, every row vector in the array will have to have the same number of columns, so you can use:

``````int p = cols(X)
``````

If instead you wanted the number of row vectors in the array, you can use `size(X)`

1 Like