# Vectorise recursion

Hello,

For my problem at hand, I consider A groups and N time-points. I calculate a matrix \Delta x of dimensions N\times A and I wish to calculate the entries of the matrix x with dimensions N\times A as follows:

x_{0,j} = 0, j\in \{1,\ldots, A\}\\ x_{1,j} = \Delta x_{1,j}, j\in \{1,\ldots, A\}\\ x_{t,j} = x_{t-1,j} + \Delta x_{t,j} , t\in \{2,\ldots, N\}

I provide below part of the code in the transformed parameters block. FORMULATION~1 is the straightforward way for implementation. I wish to vectorise this recusion, and I do that using
FORMULATION~2.

I perform two MCMC runs, one using FORMULATION~1 and the other using FORMULATION~2, with the same setting (seed, etc). Upon visual inspection I observe that the posterior median trajectories of x slightly differ between FORMULATION~1 and FORMULATION~2. Further checks related to my domain indicate that I should trust FORMULATION~2.

So I am wondering, why don’t the two formulations give equivalent posterior outputs?

I am working with rstan v2.21.3.

Thank you.

transformed parameters{
matrix[A, A] cov_mat;
matrix[N, A] delta_x_mat;
matrix[N, A] x_mat = rep_matrix(0.0, N, A);

//---- FORMULATION 1:
delta_x_mat[1,] = ....;
x_mat[1,:]      = delta_x_mat[1,:];

for(t in 2:N) {
delta_x_mat[t,] = ...;
x_mat[t,]       = x_mat[t-1,] + delta_x_mat[t,];
}

//---- FORMULATION 2 (vectorised):
for(t in 1:N) delta_x_mat[t,] = ...;
x_mat[1,:] = delta_x_mat[1,:];

for (j in 1:A) x_mat[2:N,j] = x_mat[1:(N-1),j] + delta_x_mat[2:N,j];
}