help-octave
[Top][All Lists]
Advanced

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

Re: Simple (and probably stupid) question about for loops


From: Maynard Wright
Subject: Re: Simple (and probably stupid) question about for loops
Date: Fri, 28 May 2010 08:17:06 -0700
User-agent: KMail/1.9.1

On Friday 28 May 2010 02:54, CdeMills wrote:
> AlbFrigerio wrote:
> > OK, thanks everybody for your replies. Maynard, you are completely right
> > : I was just thinking in C , not in Octave !!! It doesn't matter, I'll
> > use another way to solve the problem.
> >
> > Dear Andy, your idea is very good, but my example was very stupid. In my
> > real problem I don't know a priori which would be the values of the
> > counter to be skipped, I'll found it in the loop itself. Hence the while
> > statement is good (it's my own idea) while the for loop on [1,2...] won't
> > work.
>
> There are many ways to do that:
> 1) place a test inside the loop to execute instructions based upon some
> conditional:
>     for k=1:10
>       if k < 3 || k > 4
>         k
>      endif
>     endfor
> 2) use the "continue" or "break" to skip parts of the loop
>     for k=1:10
>       if k> 2 && k < 5 continue; endif
>       k
>     endfor
> 3) vectorise the loop
>     myloop =  (1:10); myloop(myloop > 2 & myloop < 5) = []; %# remove some
> elems
>     for k = myloop,
>       k
>     endfor
>
> Regards
>
> Pascal

These ideas will all work, but if you use a for loop, you cannot modify the 
behavior of the looping variable, or the number of iterations, but must use 
other tests within the loop to accomplish what is needed.  A while loop will 
allow you to change the variable that while is testing, maybe (??) leading to 
some simpler code.  Without seeing the actual problem of interest, it's hard 
to know for sure.

A while loop that produces the desired behavior for the example:

k=1;
while(k<=10)
   k++
   if k == 3 
      k = 6;
   endif
endwhile

Note that the output of "k++" is "ans = 2" when k = 2.  If you want an 
output "k = 2," then change the code to:

k=1;
while(k<=10)
   k
   k++;
   if k == 3 
      k = 6;
   endif
endwhile


Regards,

Maynard Wright


reply via email to

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