Vectorisation on matrices

I have a model of the type

for(I in 1:I){
 for(j in 1:J){
     target += multinomial_lpmf(y[I,j]|pi_);
 }}

I can make the code more efficient by using the vectorisation trick (Stan User’s Guide)

for(I in 1:I){
 vector[J] sum1;
 for(j in 1:J){
     sum[j] = multinomial_lpmf(y[I,j]|pi_);
 }
target += sum(sum1);
}

However,

matrix[I,J] sum1;
for(I in 1:I){
 for(j in 1:J){
     sum[i,j] = multinomial_lpmf(y[I,j]|pi_);
 }
}
for(I in 1:I){
 vector[J] sum1;
 for(j in 1:J){
     sum[j] = multinomial_lpmf(y[I,j]|pi_);
 }
}
target += sum(sum1);

so that the sum is over elements of the full matrix?
Geir

[edit: escaped Stan code]

I’m just guessing at your full model as you don’t provide data declarations. If it looks like this, where y is an array of If your multinomial is fixed, you can just add all of the y entries up in transformed data:

data {
  array[I, J, N] int<lower=0> y;
}
transformed data {
  array[N] int<lower=0> y_total = rep_array(0, N);
  for (i in 1:I) {
    for (j in 1:J) {
      for (n in 1:N) {
        y_total[n] += y[i, j n];
      }
    }
  }
}
model {
  y_total ~ multinomail(pi_);
}

But if it’s this:

data {
  array[I, J] int<lower=0> y;
}
transformed data {
  array[J] int<lower=0> y_total = rep_array(0, J);
  for (i in 1:I) {
    for (j in 1:J) {
      y_total[j] += y[i, j];
    }
  }
}
model {
  y_total ~ multinomial(pi_);
}

As you had it, the variable I was being used as the loop variable and the bound, which shouldn’t even compile in Stan.