Prevent looping variable from updating in a for loop
4 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
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
0 件のコメント
その他の回答 (1 件)
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
0 件のコメント
参考
カテゴリ
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!