Re: Trouble with a loop [message #67674] |
Fri, 14 August 2009 07:02  |
pgrigis
Messages: 436 Registered: September 2007
|
Senior Member |
|
|
On Aug 14, 9:14 am, Allan Whiteford
<allan.rem...@phys.remove.strath.ac.remove.uk> wrote:
> David Baker wrote:
>> I'm hoping someone on here maybe able to help me with a problem i'm
>> having trying to construct the following type of loop
>
>> FOR i=0,end DO BEGIN
>> IF x GT y THEN BEGIN
>> FOR j=0,end DO BEGIN
>> some program statements
>> ENDFOR
>> end=end-1
>> b=b+1
>> i=i-1
>> ENDIF
>> ENDFOR
>
>> Now the problem i'm facing is that although the i value is correctly
>> changed IDL is unaware that the limits of the for loop have been
>> decrease (i,e the value end doesn't appear to be updated when checking
>> i against it for the for loop thus leaving me in a recurring loop.)
>
>> Does anyone have any advice/ideas?
>
>> Many thanks,
>> David
>
> David,
>
> Using a variable called "end" is a really bad idea from the start, it's
> a reserved word.
>
> That aside, you want a "while" construct rather than a "for" construct:
>
> i=0
> while i++ le endvar DO BEGIN
> IF x GT y THEN BEGIN
> FOR j=0,endvar DO BEGIN
> some program statements
> ENDFOR
> endvar=endvar-1
> b=b+1
> i=i-1
> ENDIF
> ENDFOR
>
> It's also poor form and a bit rude to change your loop variable inside
> of a for loop (i.e. your line saying i=i-1) although this is normally
> considered ok inside a while.
>
> I suspect you need to take a step back and ask what you're trying to do
> with this code. It's hard for us to tell because we don't know what
> "some program statements" are and how they relate to x and y. It looks
> to me like it's almost "endvar"/"end" which should be the loop variable.
>
> Hope this helps.
>
> Thanks,
>
> Allan
Also, alternatively, if you need end(var) to decrease,
in IDL you can do something like:
for k=10,1,-1 do stuff
This will make k take the values of 10, 9, ..., 2, 1
Ciao,
Paolo
|
|
|