# Add a column to a matrix as a function of the other columns

I was wondering if its possible to add a column to a matrix by a formula that uses all other columns, like this:

{a1,b1,c1,f(a1,b1,c1)}
{a2,b2,c2,f(a2,b2,c2)}
{a3,b3,c3,f(a3,b3,c3)}


Thanks!

-
Take a look at Elegant operations on matrix rows and columns. –  FrenzY DT. Dec 11 '13 at 1:16
Also {##, f[##]}& @@@ M will do. –  Kuba Dec 11 '13 at 1:42

Since Kuba chose not to post his comment as an answer, and since Community♦ has bumped this question because of no positively voted answers, here is his method in an answer, with explanation.

You can use Apply at level one, shorthand @@@, to easily access parts of an expression via Slot and SlotSequence. Example:

dat = Partition[Range @ 9, 3]

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

{##, f@##} & @@@ dat

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


## represents the sequence of all arguments of the Function.

You could also use these:

MapThread[Append, {dat, f @@@ dat}]

Join[dat, List /@ f @@@ dat, 2]

-
A = {{a1, b1, c1}, {a2, b2, c2}, {a3, b3, c3}}
c = f @@@ A
Insert[A // Transpose, c, 4] // Transpose // MatrixForm


A, which is {{a1, b1, c1}, {a2, b2, c2}, {a3, b3, c3}}, is actually

List[List[a1, b1, c1], List[a2, b2, c2], List[a3, b3, c3]]


By replacing the inner List-s with your function using apply on level 1, a.k.a @@@.

Thus c = f @@@ A would give

c = List[f[a1, b1, c1], f[a2, b2, c2], f[a3, b3, c3]]


which is

c = {f[a1, b1, c1], f[a2, b2, c2], f[a3, b3, c3]}


Next, you transpose the original matrix and attach this newly created row using Insert, then transpose the result to get your desired matrix.

Edit: If you have a $3\times5$ matrix and you like to perform function f on the 2nd, 1st and 5th column, try this:

c = f @@@ A[[All, {2, 1, 5}]]

-
Thanks for the fast answer! I'm having trouble applying the module, it just puts it in as text it seems. –  VdeVen Dec 11 '13 at 2:04