Draw random numbers from pre-specified probability mass function in Matlab

前端 未结 1 1994
遥遥无期
遥遥无期 2020-12-07 04:30

I have a support (supp_epsilon) and a probability mass function (pr_mass_epsilon) in Matlab, constructed as follows.

supp_epsilon=[         


        
相关标签:
1条回答
  • 2020-12-07 04:40

    Using the Statistics Toolbox

    The randsample function can do that directly:

    result = randsample(supp_epsilon, n, true, pr_mass_epsilon);
    

    Without using toolboxes

    Manual approach:

    1. Generate n samples of a uniform random variable in the interval (0,1).
    2. Compare each sample with the distribution function (cumulative sum of mass function).
    3. See in which interval of the distribution function each uniform sample lies.
    4. Index into the array of possible values

    result = supp_epsilon(sum(rand(1,n)>cumsum(pr_mass_epsilon(:)), 1)+1);
    

    For your example, with n=1e6 either of the two approaches gives a histogram similar to this:

    histogram(result, 'normalization', 'probability')
    

    0 讨论(0)
提交回复
热议问题