# Vectorisation on matrices

**URL:** <https://discourse.mc-stan.org/t/vectorisation-on-matrices/35756>\
**Category:** Modeling\
**Tags:** rstan\
**Created:** [July 4, 2024, 8:32am UTC](https://discourse.mc-stan.org/t/vectorisation-on-matrices/35756 "2024-07-04T08:32:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![geirstorvik](https://avatars.discourse-cdn.com/v4/letter/g/b38774/32.png) [@geirstorvik](https://discourse.mc-stan.org/u/geirstorvik)\
**Post date:** [July 4, 2024, 8:32am UTC](https://discourse.mc-stan.org/t/vectorisation-on-matrices/35756/1 "2024-07-04T08:32:44Z")

</div>

I have a model of the type

```stan
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](https://mc-stan.org/docs/2_18/stan-users-guide/vectorization.html))

```stan
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,

```stan
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]

---

<div class="post-metadata">

**Author:** ![Bob\_Carpenter](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/bob_carpenter/32/9230_2.png) [@Bob\_Carpenter](https://discourse.mc-stan.org/u/Bob_Carpenter)\
**Post date:** [July 11, 2024, 8:51pm UTC](https://discourse.mc-stan.org/t/vectorisation-on-matrices/35756/2 "2024-07-11T20:51:01Z")

</div>

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:

```stan
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:

```stan
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.
