MATLAB: Error in loop: Attempted to access X(5); index out of bounds because numel(X)=4

attempted to acceserror in loopindex out of boundsloop

I tried searching, but don't seem to see any solutions for my problem. I have the entire code attached in a file, along with a valid data example.
In the following
for l = 1 : length(X) % uses the letter L
if X(l) < 20 || X(l) > 200 || Y(l) < 50 || Y(l) > 500 ...
|| any(a{l} < 0) || any(a{l} > 360) ...
|| any(N{l} < 0) || any(N{l} > 50)
X(l) = [];
Y(l) = [];
a{l} = [];
N{l} = [];
fprintf('Error in test subject %d, discarding dataline.\n',l)
end
end
I get an error
Error in test subject 3, discarding dataline.
Attempted to access X(5); index out of bounds because numel(X)=4.
In this example there are datalines to go through. It 'deletes' each not-valid dataline, but unless it is the last dataline only that is discarded, this error will appear. Any way to solve this? The attached .m shows how i made the function (do tell if you want me to just c/p it here instead!).

Best Answer

Yes, a very common error in coding logic everybody makes when starting out...when you process from the beginning and remove a row, then you've just shortened the size of the array. Couple of ways to go at it; the simplest is simply to begin at the end and work forward...
for i=length(x):-1:1
if condition, x(i)=[]; end
end
Another is to keep a list of the bad locations and wait until the end and do them all at once't...
ix=[];
for i=1:length(x)
if condition, ix=[ix;i]; end
end
x(ix)=[];
Or, same idea, vectorize the test and eliminate the loop...
ix=logicaltest(x); % return logical vector of lines to kill
x(ix)=[];
Or, of course, you can reverse the test logic and find those to keep instead.