3
$\begingroup$

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).

$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$
    – Edmund
    Commented Sep 27, 2017 at 22:57
  • $\begingroup$ @Edmund Sorry, my bad. $\endgroup$
    – Filburt
    Commented Sep 27, 2017 at 22:59

2 Answers 2

4
$\begingroup$
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}}}
$\endgroup$
2
  • $\begingroup$ You stalker! :-) Second time in one day. $\endgroup$
    – Edmund
    Commented Sep 27, 2017 at 23:04
  • $\begingroup$ Indeed, you are a wizard. $\endgroup$
    – Filburt
    Commented Sep 27, 2017 at 23:14
3
$\begingroup$

You may use Outer with ArrayFlatten.

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

Mathematica graphics

Hope this helps.

$\endgroup$
1
  • $\begingroup$ Thank you Edmund. =D $\endgroup$
    – Filburt
    Commented Sep 27, 2017 at 23:15

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.