# MATLAB: Can we vectorize a procedural for/if operation

conditionalvectorize

Howdy, I am running the following code and wonder if can vectorize to speed up:
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:length(pop_matrix)    if rand_num < sum(divid(1:i))       pop_matrix(i) = pop_matrix(i)+1;       break    endend
Thanks a lot!

 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); if ~isempty(idx)     pop_matrix(idx) = pop_matrix(idx) + 1; end
 cumsum(divid) ans =         0.05          0.1          0.2          0.4          0.5          0.6
 mySum = 0; for k = 1:length(pop_matrix)    mySum = mySum + divid(k);    if rand_num < mySum       pop_matrix(k) = pop_matrix(k)+1;       break;    end end