For loop question.
16 views (last 30 days)
Show older comments
When looping over indices of an array I use 1:length(x),
x = rand(1,10); for i = 1:length(x) ... end
is there a more efficient way?
0 Comments
Answers (2)
Jan
on 25 Aug 2011
There is no more efficient way.
As Walter mentioned already accessing the indices is faster, when you use integer types. But then you have to think twice, or better 8 times, if a saturation is possible. If you are in doubt, use at least UINT32 or stay at doubles. Example:
No advantage for integers:
x = rand(1, 1e4);
for i = 1:1e4
y = x(i);
end
for i = uint32(1):uint32(1e4)
y = x(i); % <- same speed as DOUBLE index
end
An integer loop index is faster, if it is used for indexing inside the loop:
x = rand(1, 1e4);
for i = 1:1e4
y = sum(x(1:i));
end
u1 = uint32(1);
for i = uint32(1):uint32(1e4)
y = sum(x(u1:i)); % <- faster than DOUBLE index vector
end
But the integer saturation does not cause an error message:
for i = uint8(1):uint8(1e4) % !!! uint8(1e4) is 255!
Creating the index vector explicitly is slower:
v = 1:1e4;
for i = v % Slower
y = x(i);
end
for i = 1:1e4 % Faster
y = x(i);
end
Using an explicit data vector can be nicer, but the speed depends on the details:
v = rand(1,1e4);
for av = v
y = av;
end
Walter Roberson
on 25 Aug 2011
Better practice would be 1:numel(x) but otherwise what you are doing is fine.
Jan would probably point out that using uint32() indices are faster when they are sufficient to hold the index values.
1 Comment
Jan
on 25 Aug 2011
@Walter: This is my "answer of the week"! I'm amused, that you do not create just your own answers, but even take into consideration the usual attitudes of other contributors. Thanks :-)
I'd prefer INT8 when the indices are in the range of 1 to 10. On the other hand a beginner will be confused by such tricks and the total program time (design phase + programming + testing + debugging + run time) will increase.
See Also
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!