Applying exponentiation to vectorized form avoiding for loop

Hi Everyone,

is there a way to apply exponentiation to vectors without using for loop?

for example,

I have,

model{
vector[100] p;
vector[100] q;

q = p^3.02;

}

How can I do this without for loop like this,

for (n in 1:100) {
q[n] = p[n] ^ 3.02;
}

Looking forward for an efficient solution to avoid using for loop.

Thanks,

There is no elementwise power operator in the Stan language, but if there were it would evaluate to the same loop as

for (n in 1:100) q[n] = p[n] ^ 3.02;
2 Likes

so there is no way for me to avoid the for loop when I have to use the power operator?

Given that Stan for loops are translated to C++ there is no drop in performance. And I don’t think there is any linear algebra stuff for making AD any faster with elementwise operations (I could be wrong).

Bottom line: for loops are not slow in Stan. In some cases vectorized stuff has better AD properties and are then recommended.

2 Likes

I have to use a lot of separate for loops in my model because of the power operator at different parts of my model equation.

Hence, trying to find an alternative to make it vectorized

Maybe create a user function for it?

2 Likes