From: Sean Douglas on
hey guys, i have a question regarding if statments and indexing.
Can i use an if statement to effect indexing. i have code that works if i make an index with one of the options below, but if I make an if statment it does not seem to work, so i am wondering if i can even do what i did below?

if (file1==1)
jj=(i+1)
jjj=(p+1)
elseif(file1==-1)
jj=(i)
jjj=(p)
end

thank you very much
From: Andy on
"Sean Douglas" <seanjdouglas(a)hotmail.com> wrote in message <i1hv26$q04$1(a)fred.mathworks.com>...
> hey guys, i have a question regarding if statments and indexing.
> Can i use an if statement to effect indexing. i have code that works if i make an index with one of the options below, but if I make an if statment it does not seem to work, so i am wondering if i can even do what i did below?
>
> if (file1==1)
> jj=(i+1)
> jjj=(p+1)
> elseif(file1==-1)
> jj=(i)
> jjj=(p)
> end
>
> thank you very much

If you want that sort of control over the indexing, you should try a while loop.

But why don't you post your whole loop, not just the if statement? And if you explain what it is you're actually trying to do, there may be a better way than what appears to be a triple for loop.
From: someone on
"Sean Douglas" <seanjdouglas(a)hotmail.com> wrote in message <i1hv26$q04$1(a)fred.mathworks.com>...
> hey guys, i have a question regarding if statments and indexing.
> Can i use an if statement to effect indexing. i have code that works if i make an index with one of the options below, but if I make an if statment it does not seem to work, so i am wondering if i can even do what i did below?
>
> if (file1==1)
> jj=(i+1)
> jjj=(p+1)
> elseif(file1==-1)
> jj=(i)
> jjj=(p)
> end
>
> thank you very much

The above is correct MATLAB code.
It should do EXACTLY what you have programmed it to do.
However, you should consider what might happen
if file1 is some value other than 1 or -1.
Something like:

if (file1==1)
jj=(i+1)
jjj=(p+1)
elseif(file1==-1)
jj=(i)
jjj=(p)
else
jj=? % i or i+1?
jjj=? % p or p+1?
end
From: Andy on
> The above is correct MATLAB code.
> It should do EXACTLY what you have programmed it to do.

I don't think so. In a for loop, MATLAB controls the looping variable. E.g.

for ix=1:10
if ix==5
ix=9;
else
ix
end
end

Even though it looks like it might print out 1, 2, 3, 4, 9, 10, in fact it will print out 1, 2, 3, 4, 6, 7, 8, 9, 10.

What was given in the OP is correct MATLAB code. But under the assumption it is inside a for loop, it likely doesn't do what it's intended to do.
From: Andy on
From the documentation for "for":

"Avoid assigning a value to the index variable within the body of a loop. The for statement overrides any changes made to the index within the loop."