For loop faster than vectors?
Show older comments
I was thinking that for loops were usually slower than vector or matrix operations, but a simple example showed me the opposite.
Here is a comparison of different implementations of a counter. The results for five runs of the code below are the following:
0.0730 0.0608 0.0691
0.0705 0.0543 0.0669
0.0745 0.0546 0.0709
0.0756 0.0571 0.0798
0.0755 0.0573 0.0729
I am surprised to see that the function equation1 (multiplication of a vector by a scalar) is slower than counter (for loop).
I am also surprised to see that the function equation1 is slower than equation2, just because of the vector is stored in a variable.
Does anyone have an explanation?
N = 10^7;
step = 0.123456789;
f1 = @() equation1(step, N);
t1 = timeit(f1);
f2 = @() equation2(step, N);
t2 = timeit(f2);
f3 = @() counter(step, N);
t3 = timeit(f3);
disp([t1 t2 t3])
% Functions under test
function out = equation1(step, N)
n = 1:N;
out = n * step;
end
function out = equation2(step, N)
out = (1:N) * step;
end
function out = counter(step, N)
out = zeros(1,N);
out(1) = step;
for n = 2:N
out(n) = out(n-1) + step;
end
end
1 Comment
Jérôme
on 17 Sep 2021
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!