Generating `Array` of random values from `Array` of Distributions

I have an Array (of arbitary size) containing the parameters corresponding to the parameters of a distribution. In this example, the Array has size (4, 3, 2) but could e.g. be size (3, 2) or (5, 2, 3, 2), etc.

For example,

using Distributions, StatsFuns
srand(1)
# pars[:, :, 1] correspond to mean
# pars[:, :, 2] correspond to standard deviation
pars = rand(Normal(), 4, 3, 2) 

pars[:, :, 2] = softplus.(pars[:, :, 2]) # put standard deviations on positive scale

# sample from normal distribution 
n = 2 # number of samples to draw from each Normal
rand.(Normal.(pars[:, :, 1], pars[:, :, 2]), n)
4×3 Array{Array{Float64,1},2}:
 [0.237169, 1.56555]    [-0.866088, -0.343568]  [0.319532, 0.475234]
 [0.34833, 0.0352314]   [0.400087, 0.430776]    [0.513749, 0.830742]
 [-1.71771, -0.646454]  [2.58106, 1.80743]      [2.46338, 1.99188]
 [-0.120796, -1.42402]  [-2.5226, -2.96022]     [1.17088, -0.0516749]

This gives me a an Array of Arrays. What I would like is a 4x3xn Array. How can I go about reshaping this Array?

1 Like

I will assume you meant to have the first values of each element in the array part of the Matrix in the first element along the third dimension and the second element as such. If that is the case you can do:

output = Array{Float64}(4,3,n)
for idx in 1:n
    output[:,:,idx] = map(elem -> elem[idx], array)
end
output
4×3×2 Array{Float64,3}:
[:, :, 1] =
  0.237169  -0.866088  0.319532
  0.34833    0.400087  0.513749
 -1.71771    2.58106   2.46338 
 -0.120796  -2.5226    1.17088 

[:, :, 2] =
  1.56555    -0.343568   0.475234 
  0.0352314   0.430776   0.830742 
 -0.646454    1.80743    1.99188  
 -1.42402    -2.96022   -0.0516749