For loop question.

조회 수: 20 (최근 30일)
Frank
Frank 2011년 8월 25일
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?

답변 (2개)

Jan
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
  댓글 수: 1
Andrei Bobrov
Andrei Bobrov 2011년 8월 25일
+1

댓글을 달려면 로그인하십시오.


Walter Roberson
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
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by