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?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communitySuppose 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?
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}]
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.
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]]
f[x, y, z]
to see what happens? $\endgroup$