For loop question.
20 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Jan
2011-8-25
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
2011-8-25
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 个评论
Jan
2011-8-25
@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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!