[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Simple (and probably stupid) question about for loops
From: |
Andy Buckle |
Subject: |
Re: Simple (and probably stupid) question about for loops |
Date: |
Tue, 25 May 2010 20:34:45 +0100 |
On Tue, May 25, 2010 at 4:30 PM, Maynard Wright <address@hidden> wrote:
> 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
>
> _______________________________________________
> Help-octave mailing list
> address@hidden
> https://www-old.cae.wisc.edu/mailman/listinfo/help-octave
>
Avoid loops if you can! However, the examples below might do something
like what you want.
k=0;
while (++k)<=10
k
if k==2
k=5;
end
end
for k=[1:2 6:10]
k
endfor
--
/* andy buckle */