Prevent looping variable from updating in a for loop

9 views (last 30 days)
Louis Vallance on 14 Dec 2012
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 on 14 Dec 2012
Edited: Evan on 14 Dec 2012
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

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