 Converting a matrix into an array

Hi all,
I would like to convert a matrix into an array. Following this How to convert a matrix to an array of vectors?, I wrote the code as:

``````transformed parameters{
matrix[J,K] theta_raw;
real theta[J,K];

theta_raw  = exp(a +b);  // a and b are J by K dimensional matrices
for(j in 1:J){
theta[j,] = theta_raw[j,];
}
}
``````

``````SYNTAX ERROR, MESSAGE(S) FROM PARSER:

Dimension mismatch in assignment; variable name = theta, num dimensions given = 1; right-hand side dimensions = 0
Illegal statement beginning with non-void expression parsed as
theta[j,  ]
Not a legal assignment, sampling, or function statement.  Note that
* Assignment statements only allow variables (with optional indexes) on the left;
* Sampling statements allow arbitrary value-denoting expressions on the left.
* Functions used as statements must be declared to have void returns
``````

This code may be valid in R, but not in Stan. I think you can write `theta[j,:] = theta_raw[j,:]`, but I’m not sure.

You can write `theta[j] = theta_raw[j]` to put the `j`th row of `theta_raw` into the `j`th row of `theta`.

Thanks @jjramsey, @hhau.
None of these suggestions worked okay. To do this I had to loop over K as well.

``````for(j in 1:J){
for(k in 1:K){
theta[j,k] = theta_raw[j,k];
}
}
``````

This slows down the code. So thought there must be a way to improve the run time.
Any other suggestions?
Thanks

Does `to_array_2d` not do what you need?:

``````real theta [J,K] = to_array_2d(theta_raw);
``````

Well, you have two parameters, `theta` and `theta_raw`, that appear to be exact copies of each other aside from them being slightly different variable types. Just the act of copying itself will bog things down, no matter how efficiently you do it, so I’d suggest avoiding that copying altogether.