Search code examples
juliadistribution

A sample for Distrubtions.jl MvNormal with N variables returns a scalar instead of tuple of size N


So I'm using 1Distributions.jl1, and I sample from a multivariant normal - I'd expect a sample for N random variables to be size N, not 1.

Here is my code - am I misinterpreting what this is doing, or is my code just wrong?

using Distributions
using LinearAlgebra
N = 3
mu =[1,1,1]
cov = Matrix(1.0I, N, N)  

d = MvNormal(mu,cov)
x =rand(d,100)
println(x[1])

When I look at the first sample, instead of being length 3, it is a scalar:

julia> include("dist.jl")
-0.02020323039551508

Solution

  • The results are returned as a Matrix not a set of tuples:

    julia> rand(d,10)
    3×10 Matrix{Float64}:
      0.99872   1.67639   2.13745  0.961745  …  1.74531   0.831261   0.104456   2.57985
     -0.503303  1.54691   1.72998  1.73453      1.02923   0.717212   2.99329    0.181151
      0.967349  0.786567  2.02966  1.02071      0.892649  3.63519   -0.374087  -0.347399
    

    x[1] just returned the first element of the matrix.

    Hence you can get the first element as (@view is to avoid data copying):

    julia> @view x[:,1]
    3-element view(::Matrix{Float64}, :, 1) with eltype Float64:
     0.7978125656624844
     1.6078955127154368
     1.376647003099504