1

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!

  • 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: http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit-loop-in-matlab-why – rayryeng Jul 15 '14 at 17:07

1 Answers1

2

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));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Ah nice. I couldn't figure out a vectorized way to do this. Agree that the `for` loop approach may be faster. – rayryeng Jul 15 '14 at 18:36
  • I rewrote the program using this, and the two had a speed ratio of 5.44 with my code being faster. I really like your idea though, it makes sense. I tried using bsxfun, but I wanted to write my own input function (didn't work at all). – user3329648 Jul 15 '14 at 18:56
  • Also, after looking at the compiler more closely, all of the extra time came from one line: `sum(randi(20,2000,100000).*bsxfun(@le,(1:2000).',A));` took almost 10 minutes to compile. – user3329648 Jul 15 '14 at 19:05