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!