# Obtaining all possible ways to concatenate matrices

With Prepend we can add a line to all matrices in a set, like this:

X = {{{1,3,7,6},{2,1,3,2},{3,1,7,2}},{{7,7,1,8},{9,3,4,2},{2,4,4,6}},{{1,6,7,1},{4,5,8,1},{5,5,7,3}}};
Map[Prepend[{1, 1, 1, 1}]]@X


This code adds the line {1,1,1,1} to each matrix of the set X.

To concatenate a given matrix 2 x 4 with each matrix of the set X we can use Prepend twice. But if

Y={{{2,6,8,2},{9,4,9,8}},{{1,7,4,2},{7,6,9,6}}}


how can I obtain all the possible concatenations of the matrices from Y with those from X (in this order)?

The order is important. Each element of the resultant set is a matrix whose first two lines are a matrix from Y and the last ones is a matrix from X, like this one:

{{2,6,8,2},{9,4,9,8},{1,3,7,6},{2,1,3,2},{3,1,7,2}}


The code have to work on n x 9 matrices (n < 5).

• You have an extra 1 in the last row of the second matrix of X. You are also missing a comma in the first row of the second matrix of Y. Commented Sep 27, 2017 at 22:57
• @Edmund Sorry, my bad. Commented Sep 27, 2017 at 22:59

Join @@@ Tuples[{Y, X}]

{{{2, 6, 8, 2}, {9, 4, 9, 8}, {1, 3, 7, 6}, {2, 1, 3, 2}, {3, 1, 7, 2}},
{{2, 6, 8, 2}, {9, 4, 9, 8}, {7, 7, 1, 8}, {9, 3, 4, 2}, {2, 4, 4, 6}},
{{2, 6, 8, 2}, {9, 4, 9, 8}, {1, 6, 7, 1}, {4, 5, 8, 1}, {5, 5, 7, 3}},
{{1, 7, 4, 2}, {7, 6, 9, 6}, {1, 3, 7, 6}, {2, 1, 3, 2}, {3, 1, 7, 2}},
{{1, 7, 4, 2}, {7, 6, 9, 6}, {7, 7, 1, 8}, {9, 3, 4, 2}, {2, 4, 4, 6}},
{{1, 7, 4, 2}, {7, 6, 9, 6}, {1, 6, 7, 1}, {4, 5, 8, 1}, {5, 5, 7, 3}}}

• You stalker! :-) Second time in one day. Commented Sep 27, 2017 at 23:04
• Indeed, you are a wizard. Commented Sep 27, 2017 at 23:14

You may use Outer with ArrayFlatten.

res = Flatten[Outer[ArrayFlatten[{{#1}, {#2}}] &, y, x, 1], 1];
MatrixForm /@ res


Hope this helps.

• Thank you Edmund. =D Commented Sep 27, 2017 at 23:15