按照自定义分布生成随机数

3
我需要按照我选择的分布绘制随机数。 例如:从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中有一个函数可以从正态分布中绘制随机数; 有没有办法进行适应?

3
请参见在MATLAB中生成加权随机数 - chappjc
4个回答

8

您可以使用统计工具箱中的randsample,如此处所述

%%// 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
我只是回答了这个问题。+1 - chappjc
如果您检查分布,它将不会是所请求的分布。 - Robert Seifert
3
目的是从自定义分布中以一定概率生成数字,而不是生成具有特定分布的样本。请注意原帖作者关于使用现有函数从正态分布中生成数字的评论。 - chappjc
1
+1 我总是忘记 randsample - Luis Mendo

1
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

1

0

如果您没有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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接