Solution to dimension mismatch error when passing array of matrix from R to Stan

Yesterday, I write a post on dimension mismatch error found when passing an array of matrix from R to Stan. The error is caused by difference in syntax of array index between R and Stan.

I’ve created a workaround to this dimension mismatch problem. The solution is that instead of passing an array of matrix from R to Stan, I pass a vector of all the elements of all the matrix in the array from R to Stan. In the Stan code, the vector of all elements is transformed to an array of row vectors for all the matrix, and then the array of row vectors is transformed to an array of matrix, which is what the model desired. All the transformation above is done in the “transformed data” block.

The following is the silly example to illustrate this workaround:

data {
  int<lower=1> I;
  int<lower=2> J;
  int<lower=1> T;
  vector[I*J*T] X;

transformed data{
 row_vector[I] X_array_vector[J*T];
 matrix[J,I] X_array_matrix[T];
  //array -> array of vectors
  for(i in 1:J*T){
    for(j in 1:I){
      X_array_vector[i,j] = X[I*i-I+j];

  //array of vectors -> array of matrix
  for(t in 1:T){
    for(j in 1:J){
      X_array_matrix[t,j] = X_array_vector[J*t-J+j];

The R code is:

options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)

setwd("/Users/tc/Desktop/Research/Parameter Estimation/step1")

J <- 2
I <- 2
T <- 1

X <- c(1,2,3,4)

fit = stan('test_pass_matrix.stan',data=list(X=X,I=I,J=J,T=T))

If any experts find any issues, please pointed it out and give advisable solutions.

1 Like