I’m trying to calculate some probabilities using MvNorm.
For a univariate case I would do the following to get the probabilities for a vector, all at once:
Norm_uni = Normal(2,1) #Creates the Normal dist
xvect = [2,3,4,5]
pdf.(Norm_uni, xvect) # Resutls in a vector of length 4
I want to do the same but for a multivariate case. I have the following:
mu = [2,4]
sigma = [1 0
0 2]
Norm_def = MvNormal(mu,sigma)
x = [2.5,2]
pdf(Norm_def, x) #This works just fine for a single vector
But what if I want the values for two vectors?
y = [1,1]
pdf.(Norm_def, [x,y]) #This doesn't work
I get an error if I try to do just what I did with the univariate case. I also tried to use a matrix structure instead but it also didn’t work.
Thanks!
You don’t say what the error message is, but I’m guessing that this is because currently only univariate distributions are broadcastable (make univariate distributions broadcastable by simonbyrne · Pull Request #760 · JuliaStats/Distributions.jl · GitHub). The workaround is simply to wrap the distribution in a Ref
(or a 1-component tuple), like:
pdf.(Ref(Norm_def), [x,y])
Great. This works. What is the Ref doing here? I don’t quite follow the description of Ref in the help.
From the manual:
Sometimes, you want a container (like an array) that would normally participate in broadcast to be “protected” from broadcast’s behavior of iterating over all of its elements. By placing it inside another container (like a single element Tuple
) broadcast will treat it as a single value.
Ref(x)
acts like a (cheap) zero-dimensional array of x
.