# Creating a nested matrix from two lists

I have a matrix and two lists:

matrix = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
a = {{1, 2, 2, 1}, {3, 4, 4, 3}, {8, 5, 5, 8}};
d = {{I, 2, -I}, {I, 1, -1}, {4, I, 0}};


I am trying to do write a code as psudo-code here to joined a and b and add them to matrix:

Do[matrix[[i, j]] = AppendTo[a[[i]], a[[j]]], {i, 0, 3}, {j, 0, 3}];


the desired result is as below

matrix =
{{{1, 2, 2, 1, 1, 2, 2, 1, d[[1, 1]]},
{1, 2, 2, 1, 3, 4, 4, 3, d[[1, 2]]},
{1, 2, 2, 1, 8, 5, 5, 8, d[[1, 3]]}},
{{3, 4, 4, 3, 1, 2, 2, 1, d[[2, 1]]},
{3, 4, 4, 3, 3, 4, 4, 3, d[[2, 2]]},
{3, 4, 4, 3, 8, 5, 5, 8, d[[2, 3]]}},
{{8, 5, 5, 8, 1, 2, 2, 1, d[[3, 1]]},
{1, 2, 2, 1, 3, 4, 4, 3, d[[3, 2]]},
{8, 5, 5, 8, 8, 5, 5, 8, d[[3, 3]]}}};


I would be so glad to have a way to obtain the result. Also, it will be good if I have a final matrix in horizontal shape for its sub_matrices in the nested final matrix instead of column shape for them.

-

Xavier's comment with an additional Partition gives:

Partition[Flatten /@ Transpose[{Tuples[a, {2}], Flatten@d}], Length@d]


I think this is what the OP had in mind but it doesn't correspond to the next to last row of his "desired result."

-
using of Tuples is very interesting and intelligent. – Irreversible Jan 16 at 18:12
MapThread[
Append,
{Outer[Join, a, a, 1], d},
2
]

-

Let's build your matrix in three steps.

a = {{1, 2, 2, 1}, {3, 4, 4, 3}, {8, 5, 5, 8}};
d = {{I, 2, -I}, {I, 1, -1}, {4, I, 0}};

m1 = Join[#, #] & /@ a

{{1, 2, 2, 1, 1, 2, 2, 1},
{3, 4, 4, 3, 3, 4, 4, 3},
{8, 5, 5, 8, 8, 5, 5, 8}}

m2 = ConstantArray[#, 3] & /@ m1

{{{1, 2, 2, 1, 1, 2, 2, 1},
{1, 2, 2, 1, 1, 2, 2, 1},
{1, 2, 2, 1, 1, 2, 2, 1}},
{{3, 4, 4, 3, 3, 4, 4, 3},
{3, 4, 4, 3, 3, 4, 4, 3},
{3, 4, 4, 3, 3, 4, 4, 3}},
{{8, 5, 5, 8, 8, 5, 5, 8},
{8, 5, 5, 8, 8, 5, 5, 8},
{8, 5, 5, 8, 8, 5, 5, 8}}}

matrix = MapThread[Append, {m2, d}, 2]

{{{1, 2, 2, 1, 1, 2, 2, 1, I},
{1, 2, 2, 1, 1, 2, 2, 1, 2},
{1, 2, 2, 1, 1, 2, 2, 1, -I}},
{{3, 4, 4, 3, 3, 4, 4, 3, I},
{3, 4, 4, 3, 3, 4, 4, 3, 1},
{3, 4, 4, 3, 3, 4, 4, 3, -1}},
{{8, 5, 5, 8, 8, 5, 5, 8, 4},
{8, 5, 5, 8, 8, 5, 5, 8, I},
{8, 5, 5, 8, 8, 5, 5, 8, 0}}}


This, of course, can be nested into one expression.

matrix = MapThread[Append, {(ConstantArray[#, 3] & /@ (Join[#, #] & /@ a)), d}, 2]


But it is much harder to understand how it works in that form.

### Update

Another approach to solving this problem is to break it into two parts -- to first write a helper function that can generate any single row of the desired matrix and then map that function over the two given matrices to produce the desired matrix.

helper[aRow_, dRow_] :=


matrix // MatrixForm