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

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

 Risposta accettata

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.

2 Commenti

dpb-superman, thanks! Noted all that down. Is there a list of "common errors" that appear frequently, that i can take a look at before asking the (inevitable) next question at some point?
I'm unaware of a specific list, no, altho I'm sure there are many around. These things that seem so obvious once pointed out are simply part of learning; almost everybody will have done the same or something very similar at some time in their evolution. I think it's probably a case where most of them one has to discover on their own simply as reinforcing the learning process--one can be told all these things but until experience for oneself it doesn't make the same impression.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Richiesto:

il 25 Giu 2014

Commentato:

dpb
il 25 Giu 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by