Calculate cumulative sum in stan

model {
alpha ~ normal(0,10);
sigma ~ cauchy(0,10);
b_0 ~ cauchy(0,10);
b_titer ~ cauchy(0,10);

for (n in 1:N){
vector[N] theta;
theta[n] = inv_logit(b_0 + b_titer*low[n]);

for (i in 1:100){
vector[100] theta_sep;
theta_sep[i] = inv_logit(b_0 + b_titer*(low[n]+i*(diff[n]/100)));

}

theta[n] = theta[n] + sum(theta_sep);

target += bernoulli_lpmf(infection[n] | theta[n]);

}

always error, than there is no thets_sep…

Hi! It seems your `theta_sep` variable gets reassigned every iteration during the for loop over `i` while you only define `theta_sep[i]` in every iteration. This would mean that `theta_sep[-i]` is not defined and therefore you cannot sum this. Can you try the following?

``````model {
alpha ~ normal(0,10);
sigma ~ cauchy(0,10);
b_0 ~ cauchy(0,10);
b_titer ~ cauchy(0,10);

for (n in 1:N){
vector[N] theta;
vector[100] theta_sep;
theta[n] = inv_logit(b_0 + b_titer*low[n]);

for (i in 1:100){
theta_sep[i] = inv_logit(b_0 + b_titer*(low[n]+i*(diff[n]/100)));
}

theta[n] = theta[n] + sum(theta_sep);
target += bernoulli_lpmf(infection[n] | theta[n]);
}
``````

Also, if this doesn’t work, can you copy and paste the exact error message?

You probably also want to move theta out of the n loop. For the same reason.

``````model {
vector[N] theta;
alpha ~ normal(0,10);
sigma ~ cauchy(0,10);
b_0 ~ cauchy(0,10);
b_titer ~ cauchy(0,10);

for (n in 1:N){
vector[100] theta_sep;
theta[n] = inv_logit(b_0 + b_titer*low[n]);

for (i in 1:100){
theta_sep[i] = inv_logit(b_0 + b_titer*(low[n]+i*(diff[n]/100)));
}

theta[n] = theta[n] + sum(theta_sep);
target += bernoulli_lpmf(infection[n] | theta[n]);
}
}
``````
1 Like

Yes, good catch!

yeah, I changed, works now, thanks all :p

1 Like