Defining priors for k-dimensional arrays

I want to define priors for a k-dimensional array, such as


parameters{
    array[dim1, dim2, dim3] real param;
}

model {
  param ~ beta(3, 3); 
} 

But stan is complaining with an error, I can only define the priors using a loop, for each parameter. I don’t have an issue with defining the loop.


parameters{
    array[dim1, dim2, dim3] real param;
}

model {
  for(i in 1:dim1){
    for(j in 1:dim2){
        for(k in 1:dim3){
            param[i, j, k] ~ beta(3, 3); 
        }
      }
  }
} 

But I am worried that it will make the code much slower since it will need to define dim1dim2dim3 priors individually.

Does anyone know if there is a big performance difference? Or if there is an alternative to making a loop?

Thanks :)

You can flatten it with to_array_1d:

to_array_1d( param ) ~ beta(3, 3);

1 Like

Ooh wow interesting approach, will that have the same result? Do you think the cost of flattening expensive or the same as loop?

You can wrap each in the function profile using cmdstanr to see what the difference is: Profiling Stan programs with CmdStanR • cmdstanr

2 Likes