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: Tue, 25 May 2010 08:30:55 -0700
User-agent: KMail/1.9.1

On Tuesday 25 May 2010 07:42, John W. Eaton wrote:
> On 25-May-2010, AlbFrigerio wrote:
> | Hi everyone, I believe I'm really rusty in using Octave cause I'm trying
> | to do a very simple thing (in my mind) but I cannot succed in it. I tried
> | to read the guide and some posts on for loops, but I haven't managed
> | anything.
> |
> | Here it is my question : is it possible to update the value of the for
> | index inside the loop?
> |
> | For example, I wrote the following code :
> |
> | for k=1:10
> |   k
> |   if k==2
> |      k=5;
> |   endif
> | endfor
> |
> | I'd like the output to be : 1 2 6 7 8 9 10 , but it always gives me 1 2 3
> | 4 ... 10 . It sounds like the k variable in the loop to be completely
> | different from the one used in the loop.
>
> It's not a different variable.  The value is reset each time at the
> top of the loop.
>
> jwe

Octave's behavior here differs from C.  If you write the comparable code in C 
it is possible to modify k within the loop and to produce the output that 
lacks the integers 3, 4, and 5.  This results from the definition of for() in 
terms of while() by K&R.  I haven't checked to see whether any subsequent 
developments in C or C++ have changed this, but my compilers support the K&R 
behavior.

Note that this doesn't mean that Octave is wrong, just different from another 
language, something we need to keep in mind if we work in both.

Maynard Wright
 


reply via email to

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