For Loop dimensions

Hi,
I am trying to re-create the following R loop in stan:

``````set.seed(101)
k <- 2
L_d <- rep(99, 2)
L_t <- round(rnorm(7-1),3)
FF <- 5
L <- matrix(rep(NA, 10), ncol = k)
p <- 100 # Get P on position L[3,1],  corresponds to L_t[2] when length(L_t)=7
idx <- 0

for(q in 1:k){
L[q,q] <- L_d[q]
for(i in (q+1):FF){
idx = idx + 1

if(idx < 2){L[i,q] <- L_t[idx]}
else if(idx == 2){L[i,q] <- p}
else if(idx > 2){L[i,q] <- L_t[idx-1]}
}
}
> L_t
[1] -0.326  0.552 -0.675  0.214  0.311  1.174
> L
[,1]   [,2]
[1,]  99.000     NA
[2,]  -0.326 99.000
[3,] 100.000  0.214
[4,]   0.552  0.311
[5,]  -0.675  1.174
``````

In stan the L[1,2] NA would be zero. The goal of the loop is to fill matrix L with values from two different vectors (L_d and L_t) but then 1 element from matrix L should be a stand-allone number P instead of a number of L_t. So L_t should be reduced by 1 element and the implementation of L_t in to matrix L should be interrupted to insert P and then continue.

In stan I think it should be:

``````parameters{
vector[7-1] L_t;
vector[2] L_d;
}
transformed parameters{
matrix[5,2] L;
{
int idx;
int FF;
int k;
int P;

idx = 0
FF = 5
k = 2
P = 100

L[1,2] = 0

for (j in 1:k) {
L[j,j] = L_d[j];
for (i in (j+1):FF) {
idx += 1;
if(idx < 2){L[i,j] = L_t[idx];}
else if(idx == 2){L[i,j] = P;}
else if(idx > 2){
L[i,j] = L_t[idx-1];
}
}
}
}
}
``````

However when applied in R the following error message occurs:
“mismatch in dimension declared and found in context; processing stage=initialization; variable name=L_t; position=0; dims declared=(6); dims found=(7)”

I think stan interpreter ignores the if(idx < 2) condition and thinks that because idx runs up to 7 than length(L_t) should also go up to 7. But idx is no longer used as a direct index because of the if-statement.
Any suggestions for replicating the R-loop-code in stan?
(end goal here is to put different constraints/priors on this singled-out parameter, P)

Are you supplying initial conditions to this model through Rstan? I think that error means you’re supplying a vector of length 7 to initialize L_t when L_t is only length 6.