Creating matrix of draws from vector of distributions

Viewed 29

I have a vector of n distributions and I am trying to create a n x t matrix of t draws from each of the n distributions.

using Distributions

d = [Uniform(0,1), Uniform(1,2), Uniform(3,4)]
r = [rand(i, 2) for i in d] # Want a 3x2 matrix, but get an array of arrays

Expected:

[0.674744 0.781853; 1.70171 1.56444; 3.65103 3.76522]

Actual:

[[0.674744, 0.781853], [1.70171, 1.56444], [3.65103, 3.76522]]
1 Answers

Try double indexing of a comprehension:

julia> using Distributions

julia> d = [Uniform(0,1), Uniform(1,2), Uniform(3,4)]
3-element Array{Uniform{Float64},1}:
 Uniform{Float64}(a=0.0, b=1.0)
 Uniform{Float64}(a=1.0, b=2.0)
 Uniform{Float64}(a=3.0, b=4.0)

julia> r = [rand(i) for i in d, _ in 1:2]
3×2 Array{Float64,2}:
 0.687725  0.433771
 1.28782   1.00533
 3.37017   3.88304

Another interesting option is to use broadcasting assignment:

julia> out = Matrix{Float64}(undef, 3, 2)
3×2 Array{Float64,2}:
 1.0735e-313   7.30082e-316
 7.30082e-316  7.30082e-316
 7.30082e-316  6.11918e-316

julia> out .= rand.(d)
3×2 Array{Float64,2}:
 0.803554  0.457955
 1.4354    1.41107
 3.31749   3.2684

This is shorter and might be useful if you need to sample many times and want an in-place operation (which is often the case in simulation modeling).

Related