Loops for multi-dimensional arrays

Hi everybody!

I have an issue with the part of the code below. I define three-dimensional array “pricing_kernel” and vector “beta”. I would like to run the loop and write the expression “exp(pricing_kernel[N,2,j]*beta)” to the corresponding shelf of the object “mm”.


data {
int<lower=0> N;             
int<lower=0> nq;             
int<lower=0> J;                        

real pricing_kernel[N,2,J]; 
}

parameters {
vector[2] beta;
}

model {

real mm[N,1,J];


//priors:
beta[1]~normal(0,1);
beta[2]~normal(-2,0.5);

for (j in 1:J) {    
   
   mm[N,1,j] = exp(pricing_kernel[N,2,j]*beta) ;  
 }
.....
}



In R it can be made easy enough:

  for (j in 1:J) {        
    mm[,,j] = exp(pricing_kernel[,,j] %*% beta );  
  }

I tried to do it in Stan in different ways, but not successfully. Could someone help with this? Thank you in advance!

Hi there!

The dimensions of your multiplication don’t quite make sense. I’d guess that you receive an error on

mm[N,1,j] = exp(pricing_kernel[N,2,j]*beta) ;

because here you are multiplying a real scalar (which is pricing_kernel[N,2,j]) with a 2-dimensional vector (beta). The result of this is a 2-dimensional vector. Then you take the exp function, which (I believe) again results in a 2-dimensional vector (the element-wise exp of the previous vector). Finally, you try to assign this 2-dimensional vector to a real scalar, mm[N,1,j].

What exactly are you trying to accomplish? If you want to accomplish the same multiplication as you have in R:

for (j in 1:J) {        
  mm[,,j] = exp(pricing_kernel[,,j] %*% beta );  
}

then the easiest way is probably to declare pricing_kernel as an array of matrices:

matrix[N,2] pricing_kernel[J];

then pricing_kernel[j] would be a matrix for every j in 1:J.

1 Like

Thank you very much for your response!
Yes, I would like to accomplish the same multiplication as in R. I had tried declaring “pricing_kernel” as you suggested, but it didn’t work out.


matrix[N,2] pricing_kernel[J];  
matrix[N,1] mm[J];
 for (j in 1:J) {    
 
   mm[j] = exp(pricing_kernel[j]*beta) ;  
 }

When I run the script, it returns the ERROR message:

"SYNTAX ERROR, MESSAGE(S) FROM PARSER:
Dimension mismatch in assignment; variable name = mm, type = matrix; right-hand side type = vector.
Illegal statement beginning with non-void expression parsed as
mm[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…"

Please try declaring mm as

vector[N] mm[J];

and let me know if that works.

Otherwise you might need to play around with the to_matrix function (see HERE ).

Thanks! It seems it works now!

1 Like

Great! Glad I could help :)

1 Like