# Computing sum(i*p[i]) without a loop

I have an int N and a vector[N] p and I’d like to compute

\sum_{i=1}^{N} i p_i.

I can do this in a loop:

real s = 0;
for(i in 1:N)
s += i*p[i];


Is there a way to do this without a loop? I tried this:

s = dot_product(1:N, p);


but I learned that 1:N means something different in Stan and in R, so this can’t work.

Insert it as a data

int N;
row_vector[N] n_range;

s = n_range * p

Don’t forget to initialize the vector, or you get nan results

Thanks Ari, good idea. That works great.

Aside: Is there a reason for using n_range * p instead of dot_product(n_range, p)?

They are same.

1 Like