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 
Return to the default flat view Create a new topic Submit Reply
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
[Message index]
 
Read Message
Read Message
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: Wed Oct 15 23:58:52 PDT 2025

Total time taken to generate the page: 2.56313 seconds