vectorizing

46 views
Skip to first unread message

Luca Campanelli

unread,
Feb 17, 2017, 11:35:19 AM2/17/17
to Stan users mailing list
Dear Stan users,
I have two different but related questions about vectorizing.

Thank you for any suggestion you may have.
Luca


1) What is the best way to vectorize the following code? fmax is not working with vectors.

for (n in 1:N)
    mu
[n] = fmax(0, my_equation);


2) What is the best way to code (vectorized if possible) the following model?

mu = my_equation, if x > beta
             
0 , if x <= beta

where:
x
= observed data
beta
= parameter


Bob Carpenter

unread,
Feb 17, 2017, 2:29:56 PM2/17/17
to stan-...@googlegroups.com
(1) can't be vectorized yet. But because there are
no derivatives in fmax and loops are just compiled to C++,
the loop will be fast. You can put it in a function if you
want the code to be simpler.

(2) will break continuous differentiability and may cause
problems for sampling or optimization if beta crosses x during
an iteration. To answer your question:

mu = x > beta ? my_equation : 0;

But if this is in a loop for mu[n], then you want to pull
our any shared subexpressions in my_equation so that you
only compute them once and reuse the result.

- Bob
> --
> You received this message because you are subscribed to the Google Groups "Stan users mailing list" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to stan-users+...@googlegroups.com.
> To post to this group, send email to stan-...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Luca Campanelli

unread,
Feb 17, 2017, 4:32:14 PM2/17/17
to Stan users mailing list
Thank you very much, Bob!

Luca


Reply all
Reply to author
Forward
0 new messages