4
$\begingroup$

To my shame, I have discovered the power of Map quite recently and since then I have been using it more and more. But increasingly I find myself trying to use Map with multiple arguments but there is no solution for this and I cannot understand why. Can anyone clarify this? What I could like is something like this:

Map[#1+#2,values for #1,values for #2]

What is it about Map that cannot achieve what Table has?

Cheers

$\endgroup$
1
  • $\begingroup$ Look for MapThread $\endgroup$ – Ulrich Neumann Jun 21 at 13:18
8
$\begingroup$

MapThreadis what you are looking for I think:

MapThread[#1 + #2 + #3 &, {{a, b, c}, {x, y, z}, {1, 2, 3}}]
(*{1 + a + x, 2 + b + y, 3 + c + z}*)
$\endgroup$
6
  • $\begingroup$ I have tried the following MapThread[#1 + #2 &,Flatten[Table[{i, j}, {i, 1, 10}, {j, 1, 10}], 1]] but I only get {2,3} out of all 100 pairs. Where are the rest? $\endgroup$ – lucian Jun 21 at 13:29
  • $\begingroup$ @lucian perhaps you need Transpose[Flatten[...]] $\endgroup$ – mikado Jun 21 at 13:31
  • $\begingroup$ HA! I think I get it now! Thank you all! $\endgroup$ – lucian Jun 21 at 13:33
  • $\begingroup$ @Ulrich it is safe to assume that no parallelization can be done with MapThread? $\endgroup$ – lucian Jun 21 at 13:41
  • 1
    $\begingroup$ @lucian Parallelize[ MapThread[#1 + #2 + #3 &, {{a, b, c}, {x, y, z}, {1, 2, 3}}]] evaluates quite slow without errormessage $\endgroup$ – Ulrich Neumann Jun 21 at 14:24
5
$\begingroup$

Combining your example in the comments and your original intentions, why not try something like this?

Map[#[[1]]+ #[[2]] &,Flatten[Table[{i, j}, {i, 1, 10}, {j, 1, 10}], 1]]

It seems that it accomplishes your want to use Map with multiple arguments.

$\endgroup$
1
  • $\begingroup$ this is great! I had no idea I can do this! I wish this was in the documentation, or at least I didn't find it $\endgroup$ – lucian Jun 21 at 21:30
4
$\begingroup$

I prefer Apply at level 1

#1 + #2 & @@@ Tuples[{Range[5], Range[5]}]

Tuples is used here to give the same effect as Table, but of course you can use any two lists (that are the same length)

Thread[{list1,list2}]

Just to show this is the same as Table (if you add a partition), evaluate this:

Block[{dim1=5,apply,table},
  apply=#1+#2&@@@Tuples[{Range[dim1],Range[2,6]}]//Partition[#,dim1]&;
  table=Table[i+j,{i,dim1},{j,2,6}];
  apply===table]

Which returns True

$\endgroup$

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