help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: For Loop Index Problems


From: Przemek Klosowski
Subject: Re: For Loop Index Problems
Date: Thu, 4 Jun 2009 16:15:35 -0400 (EDT)

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

      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,
   
Some techniques I'd recommend for debugging problems like that: 

 - use single-line compound commands; they are much easier to manage using 
   Octave's built-in command history (uparrow, edit as needed, re-execute).

 - use printf to better control printing, suppress automatic printing with ';'

I rewrote your loop as:

 for i=1:length(a),printf("-----loop i=%d-----\n",i),while 
a(i)==8,i++;printf("-while i=%d\n",i),end,printf("---i is %d\n",i), i++;end

with the following result:

-----loop i=1-----
---i is 1
-----loop i=2-----
---i is 2
-----loop i=3-----
---i is 3
-----loop i=4-----
-while i=5
-while i=6
-while i=7
---i is 7
-----loop i=5-----
-while i=6
-while i=7
---i is 7
-----loop i=6-----
-while i=7
---i is 7
-----loop i=7-----
---i is 7
-----loop i=8-----
---i is 8
-----loop i=9-----
---i is 9

so, as you reported, the for loop resets the counter to its own sequence.
If you want to change the index while looping, use while:


i=1; while i<length(a),printf("-----loop i=%d-----\n",i),while 
a(i)==8,i++;printf("-while i=%d\n",i),end,printf("---i is %d\n",i), 
i++;end-----loop i=1-----
---i is 1
-----loop i=2-----
---i is 2
-----loop i=3-----
---i is 3
-----loop i=4-----
-while i=5
-while i=6
-while i=7
---i is 7
-----loop i=8-----
---i is 8


reply via email to

[Prev in Thread] Current Thread [Next in Thread]