2015-05-07 98 views
0

我不知道下面的代码是否可以被矢量化?或者,更直接的,我试图将一个数字与几个间隔相匹配,其结果决定了增量过程的更新。非常感谢!是否可以在Matlab中矢量化程序操作(for/if)?

pop_matrix = [10 0 0 0 0 0]; 
    rand_num =rand; 
    divid = [0.05 0.05 0.1 0.2 0.1 0.1]; 

for i = 1:6 
    if rand_num < sum(divid(1:i)) 
     pop_matrix(i) = pop_matrix(i)+1; 
     break 
    end 
end 
+0

我会用向量化的代码发布一个答案,但是你能澄清你的意思吗?“匹配数个间隔”?我只是想知道是否有更简单的方法来做到这一点。 – eigenchris

+0

非常感谢eigenchris,感谢您的快速响应。 –

+0

我现在第二次猜测我的答案。当你把'break'放在那里时,你的意思是你只想检查第一个成功的间隔,但是没有一个是正确的? – eigenchris

回答

3

下面应该工作:

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 methoddivid定义的概率分布抽样,其中dcs是分布的累积密度函数(CDF)。

+0

@XiaoYi如果您计划使用代码绘制多个样本,第二个答案应该比第一个答案快。 – eigenchris