Why (in MATLAB) this code is faster?

matlab, performance

Solution

Your test setup is simply too small to show the advantages of vectorization.

Initial = [zeros(10,1) ones(10,1)];
Elapsed time is 0.000078 seconds.
Elapsed time is 0.000995 seconds.

Now for a larger problem:

Initial = [zeros(1000,1) ones(1000,1)];
Elapsed time is 2.797949 seconds.
Elapsed time is 0.049859 seconds.

Problem

I have written some code in two different ways in MATLAB. Firstly, I used two for loops, which seems stupid at the first glance: ``` Initial = [zeros(10,1) ones(10,1)]; for xpop=1:10 for nvar=1:10 Parent(xpop,nvar) = Initial(nvar,1)+(Initial(nvar,2)-Initial(nvar,1))*rand(); end end ``` In the second scheme, I tried to do vectorized computation (I assumed it can be faster): ``` Parent = repmat(Initial(:,1),1,10) + rand(10,10).*(repmat(Initial(:,2),1,10)-repmat(Initial(:,1),1,10)); ``` The elapsed time in three different run of the code can be seen following: ``` Elapsed time is 0.000456 seconds. Elapsed time is 0.006342 seconds. Elapsed time is 0.000457 seconds. Elapsed time is 0.006147 seconds. Elapsed time is 0.000471 seconds. Elapsed time is 0.006433 seconds. ``` Why is the first scheme faster than the second? Is it really doing two stupid for loops inside the '.*' command?

Original source