Copying arrays of vectors into matrices to make use of to_vector

Hello!

Suppose I have an array of vectors, eg

data{
  int T;
  int n;
}
parameters{
  row_vector[n] v[T];
}

and suppose I want to copy this into a matrix so I can use vectorised sampling statements. Which of these is more efficient?

Option 1:

model{
  matrix[T,n] A;

  for(i in 1:T){
    for(j in 1:n){
      A[i,j] = v[i,j];
    }
  }

  to_vector(A) ~ normal(....);
}

Or option 2?

model{
  matrix[T,n] A;

  for(i in 1:T){
    A[i] = v[i];
  }
}

to_vector(A) ~ normal(....);

Thanks!

It’s actually going to be faster to work with arrays of vectors and fill the matrix by column. Stan stores matrix data by column in memory, so column wise operations will be more efficient

2 Likes

Great - thank you!