如何用matlab生成服从任意有限离散分布的随机数的方法,代码如下:
function out=drnd(p,n)
%out=drnd(p,n)
%copyright:rocwoods
%p is the probability distribution matrix;
%n is the number of the samples you want to generate;
%=================
a=cumsum(p(2,: ));
b=rand(n,1);
out=zeros(1,n);
for k=1:n
c=find(a<b(k));
if (isempty(c))
out(k)=p(1,1);
else
out(k)=p(1,c(end)+1);
end
end
举例说明:
比方说一个随机变量可以取1 2 3 4 5这5个值。每个值的概率分别为0.1 0.3 0.25 0.25 0.1
则P=[1 2 3 4 5;0.1 0.3 0.25 0.25 0.1]
生成1000个样本,如下:
out=drnd(P,1000)
%结果省略