Applying Vectorization in generated quantities section

Hi Everyone,

I am trying to convert all the for loops into vectorized form so that the calculations are done faster.

But, when I try to change the for loops to vectorized form in generated quantities section, Im getting a dimension mismatch in assignment error.

My question is, vectorization is not applicable to generated quantities section?

Thanks in advance,

1 Like

Could you please post some code so we can take a look at how you’re currently attempting to do this?

1 Like

Yes, it is possible to vectorize rng functions, but as the error tells you,

you need to ensure you have matching dimensions on both sides of the rng function.

For example, given the data

data {
int N;
vector[N] y;
}

You can create the following vector of ones which you can then use on the generated quantities block to ensure your functions have the correct dimensions.

transformed data {
vector[N] ones_N = rep_vector(1, N);
}
parameters {
real <lower = 0> lambda;
}

model {
lambda ~ exponential(1);
target += exponential_lpdf(y | lambda);
}

generated quantities {
real y_rep[N]  = exponential_rng(ones_N * lambda);
}

Does, avoiding looping over every data point.

Hope it helps!

Hi@tiagocc

I will try to implement this and update tomorrow If I’m able to make my model work. Thanks for the tip

Hi @tiagocc,

Can you show an example of using the ones for normal_rng function?