从Matlab中预先指定的概率质量函数中提取随机数 [英] Draw random numbers from pre-specified probability mass function in Matlab

查看:300
本文介绍了从Matlab中预先指定的概率质量函数中提取随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matlab中有一个支持(supp_epsilon)和一个概率质量函数(pr_mass_epsilon),其构造如下.

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

supp_epsilon=[0.005 0.01 0.015 0.02]; 

suppsize_epsilon=size(supp_epsilon,2);

pr_mass_epsilon=zeros(suppsize_epsilon,1);

alpha=1;
beta=4;

for j=1:suppsize_epsilon
    pr_mass_epsilon(j)=betacdf(supp_epsilon(j),alpha,beta)/sum(betacdf(supp_epsilon,alpha,beta));
end

请注意,pr_mass_epsilon的组成部分总计为1.现在,我想从pr_mass_epsilon绘制n随机数.我怎样才能做到这一点?我想要一个适用于任何suppsize_epsilon的代码.

Note that the components of pr_mass_epsilon sum up to 1. Now, I want to draw n random numbers from pr_mass_epsilon. How can I do this? I would like a code that works for any suppsize_epsilon.

推荐答案

使用统计工具箱

randsample 函数可以直接做到这一点:

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. 在时间间隔(0,1)中生成均匀随机变量的n个样本.
  2. 将每个样本与分布函数(质量函数的累积和)进行比较.
  3. 查看每个均匀样本位于分布函数的间隔中.
  4. 索引可能的值数组
  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);


以您的示例为例,使用n=1e6两种方法中的任一种都可以得出类似于以下的直方图:


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

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

这篇关于从Matlab中预先指定的概率质量函数中提取随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆