是否可以在Matlab中对程序操作(for / if)进行矢量化?

时间:2015-05-07 19:29:11

标签: matlab

我想知道以下代码是否可以进行矢量化?或者,更简单,我试图将数字与几个间隔匹配,其结果决定了增量过程的更新。非常感谢!

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

1 个答案:

答案 0 :(得分: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的分发中抽取N个样本,使用divid的方法速度提高约10倍:

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)。