       RE: DO if Loop

• To: mathgroup at smc.vnet.net
• Subject: [mg26636] RE: [mg26593] DO if Loop
• From: "David Park" <djmp at earthlink.net>
• Date: Sat, 13 Jan 2001 22:36:14 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```Bob,

A good place for functional programming rather than a Do loop. Here is a
short example.

list = Table[{Random[Integer, {1, 9}], Random[Integer, {1, 9}],
Random[Integer, {1, 9}]}, {5}]
{{8, 4, 7}, {7, 6, 7}, {7, 1, 5}, {5, 4, 9}, {3, 1, 8}}

For a function, let's say that we want the square root of the sum of
squares. If you define the function to operate on a list of three numbers,

f[{x_, y_, z_}] := Sqrt[x^2 + y^2 + z^2]

then just Map the function onto the elements of the list.

f /@ list
{Sqrt, Sqrt, 5*Sqrt, Sqrt, Sqrt}

If your function is defined this way,

g[x_, y_, z_] := Sqrt[x^2 + y^2 + z^2]

then you have to Apply it to each triplet list and that function is mapped
onto the list.

g @@ # & /@ list
{Sqrt, Sqrt, 5*Sqrt, Sqrt, Sqrt}

In Version 4, this can be shortened to

g @@@ list
{Sqrt, Sqrt, 5*Sqrt, Sqrt, Sqrt}

Check out Map and Apply in Help.

David Park

> From: Bob Hallam [mailto:pixelpounder at earthlink.net]
To: mathgroup at smc.vnet.net
> Hello,
>
> I have a matrix function and a list of 2622 variables in groups of 3.  I
> need to apply this function to each set of 3 variables continuing until
> finished with the list.
>
> How is this done?
>
> Best Regards,
>
> Bob

```

• Prev by Date: Partial Differential Equation
• Next by Date: Variable Names
• Previous by thread: Re: DO if Loop