8
$\begingroup$

Say I have vectors {a,b,c} and {w,x,y,z}. How can I get Mathematica to output an array {{a,w},{a,x},{a,y},{a,z},{b,w},{b,x},{b,y},{b,z},{c,w},{c,x},{c,y},{c,z}} where we have all combinations of the vector components matched up. I can do this with some for loops but I'm hoping that I'm missing an easier way of doing this.

Probably, the equivalent of the expand.grid function in R. Help is much appreciated!

$\endgroup$
3
  • 13
    $\begingroup$ Tuples[{{a, b, c}, {w, x, y, z}}] $\endgroup$
    – cvgmt
    Feb 13 at 14:25
  • $\begingroup$ @cvgmt sorry, just saw your comment. Should I remove my answer? $\endgroup$
    – lericr
    Feb 13 at 16:34
  • $\begingroup$ @lericr For the convenience of the reader,keep the answer. $\endgroup$
    – cvgmt
    Feb 14 at 0:30

7 Answers 7

7
$\begingroup$
Tuples[{{a, b, c}, {w, x, y, z}}]
$\endgroup$
9
$\begingroup$

Try

Flatten[Outer[{#1, #2} &, {a, b, c}, {w, x, y, z} ], 1]
(*{{a, w}, {a, x}, {a, y}, {a, z}, {b, w}, {b, x}, {b, y}, {b, z},{c,w}, {c, x}, {c, y}, {c, z}}*)
$\endgroup$
8
$\begingroup$

Also:

Distribute[{{a, b, c},{w, x, y, z}}, List] 

{{a, w}, {a, x}, {a, y}, {a, z}, {b, w}, {b, x}, {b, y}, {b, z}, {c, w}, {c, x}, {c, y}, {c, z}}

$\endgroup$
7
$\begingroup$
Sequence @@ Thread[{#, {w, x, y, z}}] & /@ {a, b, c}

{{a, w}, {a, x}, {a, y}, {a, z}, {b, w}, {b, x}, {b, y}, {b, z}, {c,
w}, {c, x}, {c, y}, {c, z}}

$\endgroup$
6
$\begingroup$
la = {a, b, c};

lb = {w, x, y, z};

Join @@ Outer[List, la, lb]

{{a, w}, {a, x}, {a, y}, {a, z}, {b, w}, {b, x}, {b, y}, {b, z}, {c, w}, {c, x}, {c, y}, {c, z}}

$\endgroup$
4
$\begingroup$

Another way, using Through and Thread:

f = Splice@Thread[{#[[0]], #[[1]]}] & /@ Through[#1[#2]] &;

f[{a, b, c}, {w, x, y, z}]

Result:

{{a, w}, {a, x}, {a, y}, {a, z}, {b, w}, {b, x}, {b, y}, {b, z}, {c, w}, {c, x}, {c, y}, {c, z}}

Or using TensorProduct:

Sequence @@@ Map[List @@ # &, TensorProduct[{a, b, c}, {w, x, y, z}], {2}]

Result:

{{a, w}, {a, x}, {a, y}, {a, z}, {b, w}, {b, x}, {b, y}, {b, z}, {c, w}, {c, x}, {c, y}, {c, z}}

$\endgroup$
1
$\begingroup$
la = {a, b, c};

lb = {w, x, y, z};

A variant of E. Chan-López first answer using Comap (new in 14.0)

Splice @ Thread[{Head[#], First[#]}] & /@ First @ Comap[{la}, lb, {2}]

{{a, w}, {a, x}, {a, y}, {a, z}, {b, w}, {b, x}, {b, y}, {b, z}, {c, w}, {c, x}, {c, y}, {c, z}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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