【问题标题】:draw random number following a custom distribution [duplicate]在自定义分布之后绘制随机数[重复]
【发布时间】:2014-04-20 05:38:04
【问题描述】:

我需要按照我选择的分布绘制随机数。

示例:用这些概率从 1 到 7 抽取 7 个数字:

  • 1:0.3
  • 2:0.2
  • 3:0.15
  • 4:0.15
  • 5:0.1
  • 6:0.05
  • 7:0.05

因为在我的实际应用程序中,我可能需要绘制 1000 个数字,所以我需要它尽可能高效(理想情况下是线性的)。 我知道 MATLAB 中有一个函数可以从正态分布中提取随机数;有什么办法适应吗?

【问题讨论】:

标签: performance matlab random distribution probability


【解决方案1】:

如果你没有randsample,你可以像在内部一样使用histc,只是没有所有的绒毛:

N = 100;
nums = 1:7;
p = [.3 .2 .15 .15 .1 .05 .05];

cdf = [0 cumsum(p(:).'/sum(p))]; cdf(end)=1; %' p is pdf
[~, isamps] = histc(rand(N,1),cdf);
out = nums(isamps);

【讨论】:

    【解决方案2】:

    认为您也可以使用 Statistics Toolbox 中的 randsamplehere

    %%// Replace 7 with 1000 for original problem
    OUT = randsample([1:7], 7, true, [0.3 0.2 0.15 0.15 0.1 0.05 0.05]) 
    

    【讨论】:

    • 我只是在回答这个问题。 +1
    • 如果你检查分布,它不会是请求的。
    • @thewaywewalk 这个想法是从自定义分布中以一定概率抽取数字,而不是生成具有特定分布的样本。请注意 OP 的 cmets 关于从正态分布中提取的现有函数。
    • +1 我总是忘记randsample
    【解决方案3】:

    您可以使用 matlab 文件交换中的 gendist:http://www.mathworks.com/matlabcentral/fileexchange/34101-random-numbers-from-a-discrete-distribution/content/gendist.m

    这会生成 1000 个随机数: gendist([.3,.2,.15,.15,.1,.05,.05],1000,1)

    【讨论】:

      【解决方案4】:
      numbers = 1:7;
      probs = [.3 .2 .15 .15 .1 .05 .05];
      N = 1000; %// how many random numbers you want
      
      cumProbs = cumsum(probs(:)); %// will be used as thresholds
      r = rand(1,N); %// random numbers between 0 and 1
      output = sum(bsxfun(@ge, r, cumProbs))+1; %// how many thresholds are exceeded
      

      【讨论】:

        猜你喜欢
        • 2017-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-06
        • 1970-01-01
        • 2020-09-28
        • 2017-09-23
        相关资源
        最近更新 更多