4
$\begingroup$

Suppose I have the lists, x, y, and z:

x = {-0.30, -0.16, 0.65}
y = {-0.28, -0.19, 0.23}
z = {-0.15, -0.11, 0.18}

Furthermore, I have defined the following function:

f[x_, y_, z_] := x (y - z)

How can I apply the function to the lists?

$\endgroup$
1
  • 5
    $\begingroup$ Have you already tried evaluating f[x, y, z] to see what happens? $\endgroup$ May 22, 2020 at 16:21

4 Answers 4

6
$\begingroup$

Here's one way:

x = {-0.30, -0.16, 0.65};
y = {-0.28, -0.19, 0.23};
z = {-0.15, -0.11, 0.18};
f[{x_, y_, z_}] := x (y - z)
f /@ Transpose[{x, y, z}]
$\endgroup$
1
  • 1
    $\begingroup$ No particular advantage, it's just this is how I thought of doing it, and J.M. hadn't made his comment at that point. There are always lots of ways of doing things! $\endgroup$
    – bill s
    May 22, 2020 at 18:22
6
$\begingroup$

Another way

MapThread[f, {x, y, z}]
$\endgroup$
3
$\begingroup$

Here's another way:

g[l_] := f[l[[1]], l[[2]], l[[3]]]
g[x]
(* 0.243 *)

Map[g[#] &, {x, y, z}]
(* {0.243, 0.1176, 0.0435} *)

The first answer is perhaps better, I'm still starting MMA.

$\endgroup$
3
$\begingroup$

My two pennies. Since the OP wishes to apply a function, here is the code with Apply (shorthand @@):

x = {-0.30, -0.16, 0.65};
y = {-0.28, -0.19, 0.23};
z = {-0.15, -0.11, 0.18};
f[x_, y_, z_] := x (y - z) 

Then, create input value sets. For many variables (datasets), there are plenty of easy ways to do it without writing it down like I have.

set = {x, y, z}

{{-0.3, -0.16, 0.65}, {-0.28, -0.19, 0.23}, {-0.15, -0.11, 0.18}}

And Apply f over the values:

f @@ set

{0.039, 0.0128, 0.0325}

Simple evaluation f[x, y, z] also yields the same result. To evaluate for a specific set of inputs, e.g. the second (-0.16, -0.19, -0.11), then a crude way is

MapAt[f, set, 2][[2]]
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.