Unexpected matrix summation behaviour

Hi, the code below presents an unexpected behaviour to me. I declare an array of 10 2x2 matrix called “S”. If I print the first element S[1] everything seems fine. If I sum S[1] to a 3x3 matrix “R” now S[1] becomes ifself a 3x3 matrix.

My question is, shouldn’t Stan raise an error during the summarion between different sized matrices (but I suppose that the answer lies in the way that array of matrices is stored in the memory)? And also, why printing before and after the summation display a change in matrix size for S[1]?

thank you

data {}
parameters {}
transformed parameters{
  matrix[2,2] S[10];
  matrix[3,3] R = [[1,2,3], [4,5,6], [7,8,9]];
  // here S[1] is a 2x2 matrix
  print("S[1] before summation");
  // Why is this allowed? S[1] is 2x2 while R is 3x3
  S[1] = R;
  // now S[1] is a 3x3 matrix
  print("S[1] after summation");
model {

1 Like

This was unfortunately a known bug that was recently fixed (more information in this github issue).

What version of Stan are you using? If you’re using RStan, then the version currently available on CRAN is a few Stan versions behind and does not have the fix included. The recommended approach here would be to use cmdstanr instead.


Unfortunately, I get the same behaviour with cmdstanr 0.4.0:

Chain 1 S[1] before summation 
Chain 1 [[nan,nan],[nan,nan]] 
Chain 1 S[1] after summation 
Chain 1 [[1,2,3],[4,5,6],[7,8,9]]