Element wise power function for array or matrix

In the manual, I did not find element wise power function for array or matrix.

That’s correct—it’s not implemented. It is on our to-do list.

Also, I changed the tag from Developrs to Modeling as this isn’t a topic about Stan development.

Writing your own function to do it in a loop won’t be any slower than the way we do the vectorization right now. We’ll eventually get around to elminating a bunch of virtual function calls in the elementwise functions, but we don’t do that yet for anything other than the probability density and mass functions.

1 Like

Thanks Bob.

I think we can do exp(2.5*log(abs(A))) for array A to obtain A[i]^2.5.

That’s clever, but it’ll be less efficient than the loop with the call to pow(). Stan’s loops are efficient. And all log(v) for a vector v does is create a loop. So when you do this:

vector<lower = 0>[K] v;
vector[K] log_v = log(v);

It does the same thing both in terms of results and effiicency as:

vector[K] log_v;
for (k in 1:K)
  log_v[k] = log(v[k]);

The problem with using three operations (exp, multiply, and log) is that it creates a bigger expression graph to autodiff, so it’ll be slower.

P.S. I’m not sure about the abs—isn’t x^{2.5} only real-valued when x is positive

1 Like

Yes, you are right.
I just use ^2.5 as an example.
My case is just ^2, for which I consider

A .* A


Depending on what you want to do with the result, we also have functions like

dot_self(v) = sum(v .* v)

In fact, -0.5 * dot_self(y) is an efficient way to implement the log standard normal density.

Good idea.
Thank you.