22

Possible Duplicate:
How do I use Map for a function with two arguments?

If I have a function:

F[x_,y_,z_]:=x*y*z

and I want to call it with several different x values using Map (and y and z fixed), is there a way to do that with a one-liner?

That is, for these x values

xVals = {1,2,3,4}

I want to somehow get:

{F[1,10,100], F[2,10,100], F[3,10,100],F[4,10,100]}

If I can do it with Map, it would be great, because I have many cores and want to speed this up with the parallelized Map.

user
  • 397
  • 1
  • 2
  • 6
  • 2
    You may use map with a pure function, f[#,10,100]&/@ xvals. (I renamed your function to lowercase to keep with conventions.) – DavidC Oct 09 '12 at 19:56
  • +1 Thanks! Is there a way to do it in a grid (i.e. vary xvals and yvals)? – user Oct 09 '12 at 19:58
  • I want to essentially do a nested for loop to return a nested list: { forall yvals {forall xvals f[xval, yval,100]} } – user Oct 09 '12 at 20:02
  • I'm fairly certain this is a duplicate but I cannot find it. Anyone? – Mr.Wizard Oct 09 '12 at 20:26
  • @Mr.Wizard this one? http://mathematica.stackexchange.com/q/8147/8 or maybe this one: http://mathematica.stackexchange.com/q/4019/8 – Verbeia Oct 09 '12 at 21:34
  • @Verbeia the first one is probably what I was thinking of; do you agree with closing? – Mr.Wizard Oct 09 '12 at 21:38
  • 1
    @Mr.Wizard yes, in this case. Don't delete, though: the answers are good – Verbeia Oct 09 '12 at 21:40

3 Answers3

27

You may use map with a pure function:

f[#,10,100]& /@ xVals
{f[1, 10, 100], f[2, 10, 100], f[3, 10, 100], f[4, 10, 100]}

Table will also work:

Table[f[x, 10, 100], {x, xVals}]
{f[1, 10, 100], f[2, 10, 100], f[3, 10, 100], f[4, 10, 100]}

Multiple iterator form:

Table[f[x, y, 100], {x, {1, 2, 3, 4}}, {y, {5, 6, 7, 8}}]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
DavidC
  • 16,724
  • 1
  • 42
  • 94
9

You can use Outer to get a nested output list :

Outer[f[#1, #2, 100] &, {1, 2, 3, 4}, {5, 6, 7, 8}]
(* {{500, 600, 700, 800}, {1000, 1200, 1400, 1600}, 
   {1500, 1800, 2100, 2400}, {2000, 2400, 2800, 3200}} *)

However I'm not sure you can take advantage of Parallelize.

b.gates.you.know.what
  • 20,103
  • 2
  • 43
  • 84
8
F[x_, y_, z_] := x*y*z;
xVals = {1, 2, 3, 4};
yVals = {5, 6, 7, 8};

You could use thread for this:

Thread[d[xVals, yVals, 100]]
(* yields *)
{d[1, 5, 100], d[2, 6, 100], d[3, 7, 100], d[4, 8, 100]}
M.R.
  • 31,425
  • 8
  • 90
  • 281