Prevent looping variable from updating in a for loop

조회 수: 4 (최근 30일)
fsgeek
fsgeek 2012년 12월 14일
Hi guys,
I have a loop which looks like this:
for i=1:length(Sxx)
if isnan(Sxx(i))
Sxx(i)=[];
end
end
The idea is simply that it removes unusable values from an array prior to the main code acting on it. The only problem is that if the array Sxx is something like [1 3 6 NaN 9 5 2 8 NaN 10], then when the looping variable i=4 Sxx will become [1 3 6 9 5 2 8 NaN 10]. Since the array has shrunk by one element but the value of i has increased by 1, the loop will miss 9 and head straight for 5! If the 9 was a NaN, then the code will have missed it! Is there any way to set a condition whereby if isnan(Sxx(i))==TRUE then the loop holds at the current value of i and makes another pass at that value so that it doesn't skip any elements?
Thanks,
Louis Vallance

채택된 답변

Evan
Evan 2012년 12월 14일
편집: Evan 2012년 12월 14일
This can be done without looping by using logical indexing:
Sxx = [1 3 6 NaN 9 5 2 8 NaN 10];
Sxx = Sxx(~isnan(Sxx));
If you for some reason need to use a loop, you could fix this issue by using a while loop instead of a for loop. You could increment the "iteration count" only when you don't remove a NaN. Like so:
count = 1;
while count <= length(Sxx)
if isnan(Sxx(count))
Sxx(count) = [];
else
count = count + 1;
end
end

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 12월 15일
Another trick is to loop backwards.
for i=length(Sxx):-1:1
if isnan(Sxx(i))
Sxx(i)=[];
end
end

카테고리

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