Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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!

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

2 Answers 2

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]
share|improve this answer
add comment
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}]]
share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.