3

In Julia, I have an array of shape values and I would like to sample an array who's values are gamma distributed according to the corresponding shape element of my shape array. What I want is:

    shapes = [1.1, 0.5, 10]  
    scale = 1  
    x = SampleGammaWithDifferentShapes(shapes,scale)

where x[1] is sampled from a gamma distribution with shape=shapes[1], and x[2] is sampled from a gamma distribution with shape=shape[2], and so on.

Is there a built in function that allows you to do this in one line or will I have to define my own function for this? This seems like it should be a built in function.

Shep Bryan
  • 567
  • 5
  • 13

2 Answers2

6

The possibility to just broadcast any function over arrays makes it unnecessary to add special array-versions of functions. Can you do it for 1 value? Then just broadcast.

using Distributions

shapes = [1.1, 0.5, 10.]
scale = 1
x = rand.(Gamma.(shapes, scale))
Mikael Öhman
  • 2,294
  • 15
  • 21
  • That is expected. For each shape, you call `rand(g, 2)` and get an array with 2 random values, and then you broadcast that operation across all shapes. If you wish to flatten this, you can use `vcat(x...)` or `collect(Iterators.flatten(x))`. (Edit: followup comment disappared and now i look silly) – Mikael Öhman Apr 14 '21 at 00:50
  • Mikael, apologies. I had realized my mistake immediately and removed the comment right away. – singularity Apr 19 '21 at 21:52
3

The map function is useful for this.

using Random, Distributions

shapes = [1.1, 0.5, 10]  
scale = 1
n_samples = 1
x = map(x -> rand(Gamma(x,scale), n_samples)[1], shapes)
singularity
  • 335
  • 1
  • 7