5

In short, I look for a concise definition of a function in Mathematica that calculates the following:

$f\left(\begin{pmatrix}a_{11}&\dots&a_{1m}\\\vdots&\ddots&\vdots\\a_{n1}&\dots&a_{nm}\\\end{pmatrix},\left(b_1,\dots,b_p\right)\right)=\begin{pmatrix}a_{11}&\dots&a_{1m}&b_1&\dots&b_p\\\vdots&\ddots&\vdots&\vdots&\vdots&\vdots\\a_{n1}&\dots&a_{nm}&b_1&\dots&b_p\\\end{pmatrix}$

An example would be:

$f\left(\begin{pmatrix}a&b\\c&d\\\end{pmatrix},\left(e,f\right)\right)=\begin{pmatrix}a&b&e&f\\c&d&e&f\\\end{pmatrix}$

I already developed a few solutions, but none is really short and in direct use of built-in functions:

f1[matrix_, list_] := Join[#, list] & /@ matrix

This is the shortest I came up with, but I'm not sure a Map is the most sensible approach here.

f2[matrix_, {list__}] := Replace[matrix, {a__} -> {a, list}, {1}]

Less short, but directly using Mathematica functions.

f3[matrix_, list_] := Join[matrix, ConstantArray[list, Length[matrix]], 2]

Unnecessary ConstantArray.

None of these really seem to fulfil the requirement set.

Cúthalion
  • 53
  • 2

2 Answers2

5

Look at ArrayFlatten:

fn[matrix_, {x__}] := ArrayFlatten[{{matrix, x}}]

fn[{{a, b}, {c, d}}, {e, f}] // MatrixForm

$\left( \begin{array}{cccc} a & b & e & f \\ c & d & e & f \\ \end{array} \right)$

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2
aa = Array[a, {4, 4}];
bb = Array[b, {2}];

ArrayPad[#, {{0}, {0, Length@#2}}, #2] &[aa, bb]
(* or *) Distribute[{#, {#2}}, List, List, List, Join] &[aa, bb]

Mathematica graphics

kglr
  • 394,356
  • 18
  • 477
  • 896