2

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!

VdeVen
  • 21
  • 1

4 Answers4

5

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]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
3
m = {
{a1,b1,c1},
{a2,b2,c2},
{a3,b3,c3}
};
ResourceFunction["AppendColumn"][m, f@@@m] // MatrixForm

enter image description here

rhermans
  • 36,518
  • 4
  • 57
  • 149
1
list = Partition[Range @ 9, 3];

Query[All, {Splice, Apply @ f }] @ list

gives the expected result:

{{1, 2, 3, f[1, 2, 3]},
 {4, 5, 6, f[4, 5, 6]},
 {7, 8, 9, f[7, 8, 9]}}
eldo
  • 67,911
  • 5
  • 60
  • 168
1
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}]]
Frenzy Li
  • 540
  • 7
  • 15
  • 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 02:04