MATLAB: Can anyone help in this looping which has 408 number of elements in array but the last one 408th one is not executed…

for loop

for ii =2:n+1
if(nx(ii)-nx(ii-1)~=nx(ii+1)-nx(ii)||ny(ii)-ny(ii-1)~= ny(ii+1)-ny(ii))
flagarr(ii,1)= nx(ii);
flagarr(ii,2)= ny(ii);
flagarr(ii,3)=1;
count=count+1;
else
normcount =normcount+1;
flagarr(ii,1)=nx(ii);
flagarr(ii,2)=ny(ii);
flagarr(ii,3)=0;
end
how to change so that i can execute from 1 to 408 if initialized with 1 then shows can't access nx(0) and if with n+1 at maximum gives nx(409) index out of bound…tried either but can't find..please requiring experts help…
thanks in advance..

Best Answer

It's a little difficult to answer this without numbers, and your code is a bit hard to read, but let me try...
Is this code representative of what you have now?
for ii = 2:n+1
if (nx(ii)-nx(ii-1))~=(nx(ii+1)-nx(ii)) ||...
(ny(ii)-ny(ii-1))~=(ny(ii+1)-ny(ii))
flagarr(ii,1)= nx(ii);
flagarr(ii,2)= ny(ii);
flagarr(ii,3) = 1;
count = count + 1;
else
normcount = normcount + 1;
flagarr(ii,1) = nx(ii);
flagarr(ii,2) = ny(ii);
flagarr(ii,3) = 0;
end
end
I just reformatted it to make it a bit easier to read (you were also missing an END statement).
I don't know what your code is trying to do, but it looks like your IF statement will fail if you on the first iteration if you loop from 1:n, because nx(ii-1) will be index zero, which does not exist.
Consider looping from 1:n (where n is presumably 408) and then **at the front of your IF statement, add ii>1. This will force it to check ii on every loop, and if ii==1 it'll immediately skip evaluating the rest of the IF statement and fall into the ELSE condition. Note again that the ii>1 check MUST be the first condition in your IF statement for this to work, otherwise Matlab will error before it gets to the ii check, which is the problem you're currently having.
Again, I'm not exactly sure what you're trying to do and do not have numbers, but the proposed changes above would look like the following:
for ii = 1:n
if ii>1 && ...
(nx(ii)-nx(ii-1))~=(nx(ii+1)-nx(ii)) ||...
(ny(ii)-ny(ii-1))~=(ny(ii+1)-ny(ii))
flagarr(ii,1)= nx(ii);
flagarr(ii,2)= ny(ii);
flagarr(ii,3) = 1;
count = count + 1;
else
normcount = normcount + 1;
flagarr(ii,1) = nx(ii);
flagarr(ii,2) = ny(ii);
flagarr(ii,3) = 0;
end
end
All I changed is the top two lines.
Let us know if I'm mis-interpreting your code and if you need further help.
Paul Shoemaker