Reading three dimensional array in stan

Let’s say we define an array in R as follows –

temp_array = array(1, dim = c(I, J, K))

then we generate a list that contains this array in R,

temp_data_list = list(temp_array = temp_array)

then what should we do in stan to properly read in this three-dimensional array in the “data” section?

Thank you!

data {
  int<lower=0> I;
  int<lower=0> J;
  int<lower=0> K;
  int<lower=1> temp_array[I,J,K];
}

Thank you! Then what is the difference between using

temp_array[I,J,K]

and

matrix[J,K] temp_array[I]?

Or, more specifically, what should I do in R to transform the original data (three dimensional array) to fit in matrix[J, K] temp_array[I]?

You want a list of I matrices, each of which has J rows and K columns. The conceptual difference is that each element of temp_array is a matrix in Stan and thus you can do matrix operations with it.

Thank you! Now if we have an I by J matrix defined in R, then when I pass it into Stan, what’s the difference betwween

data {
  int<lower=0> I;
  int<lower=0> J;
  real temp_mat[I,J];
}

and

data {
  int<lower=0> I;
  int<lower=0> J;
  matrix[I,J] temp_mat;
}

?

Both conceptually and practically (in terms of preparing the data in R)?

The differences are

  1. You shouldn’t do the first version and should do the second one
  2. You can do matrix operations on temp_mat in the second case but not in the first case (so it is misleading to call it temp_mat.
  3. Constructing it in R is the same either way.
1 Like

Got it! Thank you!

One more thing, let’s say now I have already defined matrix[J,K] temp[L], and I wish to work on the j-th row of the i-th matrix in the list “temp”, what code should I type? Should I do temp[l][i,:] ?

Actually I have found some posts / tutorials that are related to this topic, but I didn’t find any of them providing an example about this particular issue.

temp[i][j, ]

1 Like

Thank you very much.

Now I wish to define a three-dimensional array (J by K by L) in “transformed parameter” block,

matrix[J,K] A[L];

and then assign values to it in the following way

for(l in 1:L){
for(k in 1:K){
A[l][,k] = temp_fun(J);
}
}

where temp_fun() is a function defined to be able to return a vector of length J each time, however, when I do something like this in my code, I got error message saying that

“Illegal statement beginning with non-void expression parsed as…”

Thus what might be the issues in my code that could lead to this kind of error?

Thank you!

I don’t know, but it isn’t coming from those lines.

I kept other parts unchanged, except for replacing A[l][,k] by a vector of length J –

vector[J] test_vec;

and now it works. Very odd.