MATLAB: Vectorize the following loop

findvectorizing

Hi all,
I'm trying to vectorize the following loop to speed it up
c = cumsum(weights);
A = ones(1,n);
x = rand(1,n);
for i = 1:n
j = find(c > x(i) ,1,'first');
A(i) = j;
end
where weights is an array of doubles which sum to 1 and n <= size(weights).
Any help would be grand!
B

Best Answer

n = 3e4;
weights = rand(n,1);
c = cumsum(weights/sum(weights));
A = zeros(1,n);
x = rand(1,n);
tic
for i = 1:n
j = find(c > x(i) ,1,'first');
A(i) = j;
end
toc
% WARNING: only if weights are monotonically increasing
tic
[B1,B1] = histc(x,c);
toc
tic
B2 = n-sum(bsxfun(@gt,c,x))+1; % Goes fast in out of memory
toc
isequal(A,B1+1,B2) % Don't forget to add 1 to histc result
LOOP : Elapsed time is 2.247998 seconds.
HISTC : Elapsed time is 0.005381 seconds.
BSXFUN: Elapsed time is 1.770875 seconds.