For Loop Index Problems
James Sherman Jr.
shermanj at umd.edu
Thu Jun 4 15:05:33 CDT 2009
I think you really want
while i < length(a),
stuff inside your for loop,
end
Since you're already incrementing the "i" variable, you don't need the for
loop to "push" you along.
On Thu, Jun 4, 2009 at 2:40 PM, josgau33 <skankinkid33 at gmail.com> wrote:
>
> Hello,
>
> I am having a simple problem with the for loop and its index. Basically,
> here is a simple program to illustrate the problem I am having.
>
> i=1;
> a=[1 2 3 8 8 8 3 2 1];
>
> for i=1:length(a)
> i
> while a(1,i)==8
> i=i+1;
> i
> end
> i
> i=i+1;
> i
> end
>
> This gives the output shown below:
> i = 1
> i = 1
> i = 2
> i = 2
> i = 2
> i = 3
> i = 3
> i = 3
> i = 4
> i = 4
> i = 5
> i = 6
> i = 7
> i = 7
> i = 8
> i = 5
> i = 6
> i = 7
> i = 7
> i = 8
> i = 6
> i = 7
> i = 7
> i = 8
> i = 7
> i = 7
> i = 8
> i = 8
> i = 8
> i = 9
> i = 9
> i = 9
> i = 10
>
> So from here, we can see that... When a=8, the while loop is entered, and i
> equals 7 when it leaves the while loop... We then see that i=7 right
> outside
> of the while loop, and that after i=i+1, i now equals 8. But then, the next
> iteration of the for loop sets i equal to 5, which was the next iteration
> originally (before the while loop was entered).
>
> My question is... Is there any way to avoid the resetting of the index? Is
> there some sort of for loop where the user is allowed to control the index,
> and not the computer. If not, can anybody show me modifications to the code
> that would solve this problem? I cannot seem to figure it out on my own.
> Suggestions would be helpful too. Thank you,
>
> Joseph Gauthier
> --
> View this message in context:
> http://www.nabble.com/For-Loop-Index-Problems-tp23875595p23875595.html
> Sent from the Octave - General mailing list archive at Nabble.com.
>
> _______________________________________________
> Help-octave mailing list
> Help-octave at octave.org
> https://www-old.cae.wisc.edu/mailman/listinfo/help-octave
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: https://www-old.cae.wisc.edu/pipermail/help-octave/attachments/20090604/2541cfe0/attachment.html
More information about the Help-octave
mailing list