# How to create an array from all combinations of the vector components?

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!

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

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


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}}*)


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}}

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}}

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}}

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}}

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}}