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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by