Factor Analytic Manual Example


#1

hi all,
I am trying to make the code from page 183 of the rstan manual work. It is about the factor analytic model.

data {
int<lower=2> K;
}
transformed data {
int<lower=1> K_choose_2;
K_choose_2 = (K * (K - 1)) / 2;
}
parameters {
vector[K_choose_2] L_lower;
real theta1;
}
transformed parameters {
cholesky_factor_cov[K] L;
for (k in 1:K)
L[k, k] = 1;
{
int i;
for (m in 2:K) {
for (n in 1:(m - 1)) {
L[m, n] = L_lower[i];
L[n, m] = 0;
i += 1;
}
}
}
}

model {
}

This code is a copy paste of the code in the manual which i stored in a .stan file. When I run the file in R, the for-loop of L_lower does not work due to error: “[]: accessing element out of range. index -2147483648 out of range”. This tells me that for some reason the " int i " that is set, is initially set to -214…;
How can I make sure that this just starts at 1?
Thank you in advance!


#2

If i set
int i;
i = 1;
it works. This did not work in my original model as I set this before declaring another variable (int j; ). So in case of multiple variables use:
int i;
int j;

i = 1
j = 1


#3

The way you really want to write that is:

int i = 1;
int j = 1;

What you can’t do is this:

int i;
i = 1; // not a variable declaration, so ends list of variable declarations
int j;  // Illegal!