comp.lang.idl-pvwave archive
Messages from Usenet group comp.lang.idl-pvwave, compiled by Paulo Penteado

Home » Public Forums » archive » Re: Foreach philosphy
Show: Today's Messages :: Show Polls :: Message Navigator
E-mail to friend 
Switch to threaded view of this topic Create a new topic Submit Reply
Re: Foreach philosphy [message #73718] Wed, 24 November 2010 13:16
wlandsman is currently offline  wlandsman
Messages: 743
Registered: June 2000
Senior Member
On Nov 24, 4:05 pm, Michael Galloy <mgal...@gmail.com> wrote:

>
> You *can* get access to the counting index with FOREACH:
>

Ah, thanks. The online help gave an example of using the key (third)
parameter of foreach with a hash table, and in my cursory reading I
didn't realize it could also be used as an index with simple
arrays. --Wayne
Re: Foreach philosphy [message #73719 is a reply to message #73718] Wed, 24 November 2010 13:05 Go to previous message
Michael Galloy is currently offline  Michael Galloy
Messages: 1114
Registered: April 2006
Senior Member
On 11/24/10 1:55 PM, wlandsman wrote:
> So I am trying to modernize my code by replacing FOR loops with the
> FOREACH syntax when appropriate. That way one doesn't have to
> worry about counting the number of elements, the code seems more
> readable, and it even works for temporary arrays such as arr[*,
> 3,*].
>
> But is it correct that you can't use the FOREACH syntax to update an
> array? For example, is there way to use FOREACH for the
> following code snippets?
>
> IDL> for i=0,N_elements(a)-1 do a[i] = b[i]
> or even
> IDL> for i=0,N_elements(a)-1 do a[i] = 17
>
> FOREACH doesn't give access to the counting index, and since array
> elements are accessed by value, the following doesn't work
>
> IDL> a = [1,2,3]
> IDL> foreach element, a do element=17
> IDL> print,a
> 1 2 3

You *can* get access to the counting index with FOREACH:

IDL> arr = findgen(10)
IDL> foreach a, arr, i do print, a, i
0.00000 0
1.00000 1
2.00000 2
3.00000 3
4.00000 4
5.00000 5
6.00000 6
7.00000 7
8.00000 8
9.00000 9

And you can modify an array that you are looping through:

IDL> arr2 = 2. * findgen(10)
IDL> foreach a, arr, i do arr[i] = arr2[i]

Mike
--
www.michaelgalloy.com
Research Mathematician
Tech-X Corporation
  Switch to threaded view of this topic Create a new topic Submit Reply
Previous Topic: Foreach philosphy
Next Topic: Re: Make IDL record console output to a file automatically?

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ] [ PDF ]

Current Time: Sat Oct 11 06:21:44 PDT 2025

Total time taken to generate the page: 0.24158 seconds