3
$\begingroup$

I know what you may be thinking so I use the code below to demonstrate what I intend to do.

a={a1,a2}
b={b1,b2}

(*What I don't want*)
MapThread[f[#1,#2]&,{a,b}]

(*Outputs {f[a1,b1],f[a2,b2]} *)

(*What I want*)
f1[x_,y_]:=f[#,y]&/@x
f2[x_,y_]:=f1[x,#]&/@y
f2[a,b]

(*Outputs {{f[a1,b1],f[a2,b1]},{f[a1,b2],f[a2,b2]}} *)

Basically, I want something that maps the function over every combination across the two lists that doesn't involve creating a lot of extra functions. Thank you!

$\endgroup$
  • $\begingroup$ While @kglr has provided the idiomatic answer given the list structure you desire (a matrix, i.e. a list of lists), normally the fastest way to find "every combination across the two lists" is Tuples[a, b]. Another advantage is that the resulting list is not as nested, making it easier to apply functions efficiently using vectorized operations :) Since you seem to be learning Mathematica, I just thought it would be nice to know about Tuples as well. $\endgroup$ – Marius Ladegård Meyer Dec 7 '17 at 7:56
  • $\begingroup$ Interesting ... Thank you! $\endgroup$ – Aakash Lakshmanan Dec 7 '17 at 8:04
  • $\begingroup$ Duplicate of this and this? $\endgroup$ – aardvark2012 Dec 7 '17 at 9:38
4
$\begingroup$
Transpose[Outer[f, a, b]]

{{f[a1, b1], f[a2, b1]}, {f[a1, b2], f[a2, b2]}}

$\endgroup$
  • $\begingroup$ Perfect, thank you! $\endgroup$ – Aakash Lakshmanan Dec 7 '17 at 8:04

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