I have a matrix and a list of the following

m={{a1,a2,a3},{b1,b2,b3},{c1,c2,c3},...,{z1,z2,z3}}; l={4,5,6}

I want to add lto m by taking all the possible combinations into account, so the combined matrix should look like


How may I can do this job? I think KroneckerProduct should work in this case, but the outcome with the function is a little bit different.. it produces {{a1,a2,a3,4,5,6},...,{z1,z2,z3,4,5,6}}...


2 Answers 2

m = {{a1, a2, a3}, {b1, b2, b3}, {c1, c2, c3}, {z1, z2, z3}}; 
l = {4, 5, 6};

You can also use Outer + Append:

Join @@ Outer[Append, m, l, 1]
 {{a1, a2, a3, 4}, {a1, a2, a3, 5}, {a1, a2, a3, 6}, 
  {b1, b2, b3, 4}, {b1, b2, b3, 5}, {b1, b2, b3, 6},
  {c1, c2, c3, 4}, {c1, c2, c3, 5}, {c1, c2, c3, 6},
  {z1, z2, z3, 4}, {z1, z2, z3, 5}, {z1, z2, z3, 6}}
updatedm = Flatten /@ Tuples[{m, l}]

List-of-lists variant of Tuples does this directly, you just need to flatten (or Apply@Append) entries of l for each element of output to achieve your intended result.

  • $\begingroup$ Got it! Thanks so much! $\endgroup$
    – Andeanlll
    Commented Apr 24, 2020 at 9:18

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.