1
votes

I would like to be able to further vectorize the following code to try and remove the for loop:

A = randi(5,1,100);
for X = unique(A)
    B(A==X) = sum(randi(17,sum(A==X),X),2);
end

Basically it is summing 1 to 5 (designated by A) random numbers between 1 and 17, 100 times. This happens multiple times, with B getting substituted for A in the following iteration. The number of loops increases exponentially with each step and I need to do 10^9 trials instead of just 100, so I'd like to remove as much as possible. Any help would be appreciated. Thanks!

1
You can't vectorize this as B is constantly going to be mutated at each iteration. You could however, make this into a 5 element cell array that contains the elements at each iteration if you like using arrayfun/cellfun, but that in itself is slower. Check this post out for more details: stackoverflow.com/questions/12522888/… - rayryeng

1 Answers

2
votes

Your code seems to me quite efficient already.

The following is a vectorized approach (using bsxfun), but at the expense of requiring more memory and more computations. Basically, it always sums 5 numbers, some of which have previously been made 0. I doubt it will be faster than yours:

A = randi(5,1,100e4);
B = sum(randi(17, 5, 100e4) .* bsxfun(@le, (1:5).', A));