# 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)    endend
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!).

for i=length(x):-1:1  if condition, x(i)=[]; endend
ix=[];for i=1:length(x)  if condition, ix=[ix;i]; endendx(ix)=[];
ix=logicaltest(x);  % return logical vector of lines to killx(ix)=[];