下面应该工作:
pop_matrix = [10 0 0 0 0 0];
rand_num =rand;
divid = [0.05 0.05 0.1 0.2 0.1 0.1];
idx = find(cumsum(divid) > rand_num,1);
pop_matrix(idx) = pop_matrix(idx) + 1;
编辑:使用interp1
方法,它是大约快10倍,假设你想从分布绘制N
样品称为divid
:
pop_matrix = [10 0 0 0 0 0];
divid = [0.05 0.05 0.1 0.2 0.1 0.1];
N = 1000; %// number of random samples to take
rand_num = rand(N,1); %// generate N random numbers
dcs = cumsum(divid); %// get cumulative distribution
dcs = dcs/dcs(end); %// ensure this is normalized to 1
dcs = [0,dcs]; %// put a zero in front to create a new bin
s = interp1(dcs, 1:length(dcs), rand_num, 'previous', NaN); %// draw samples
pop_matrix = pop_matrix + accumarray(s,1)'; %'//add up samples together
该过程基本上是使用Inverse Transform Sampling method从divid
定义的概率分布抽样,其中dcs
是分布的累积密度函数(CDF)。
我会用向量化的代码发布一个答案,但是你能澄清你的意思吗?“匹配数个间隔”?我只是想知道是否有更简单的方法来做到这一点。 – eigenchris
非常感谢eigenchris,感谢您的快速响应。 –
我现在第二次猜测我的答案。当你把'break'放在那里时,你的意思是你只想检查第一个成功的间隔,但是没有一个是正确的? – eigenchris