Sie sind auf Seite 1von 12

# 1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange

_
Mathematica Stack Exchange is a Here's how it works:
question and answer site for users of
Wolfram Mathematica. Join them; it only
takes a minute:

a question answer up and rise to the top

## Elegant operations on matrix rows and columns

Question

The Mathematica tutorial has a section 'Basic Matrix Operations', describing operations like transpose, inverse and determinant. These
operations all work on entire matrices. I am missing a section on basic operations on matrix rows / columns.

For example:

## 2. Extracting a row from a matrix

3. Inserting a row into a matrix
4. Adding two rows within a matrix together
5. Swapping two rows
6. Multiplying a row with a number

## And similar for columns.

What is the most elegant way to implementation of these operations? Speed is not important for me, but simplicity is.

Summary

Here I summarize my personal taste. I will update it whenever someone suggests a way I like more.

m = Range@12 ~Partition~ 3;
m // MatrixForm

1 2 3
⎛ ⎞

⎜ 4 5 6 ⎟
⎜ ⎟
⎜ 7 8 9 ⎟
⎝ ⎠
10 11 12

## Insert a column at position 2:

v = Range[21, 24];
Insert[m // Transpose, v, 2] // Transpose // MatrixForm

1 21 2 3
⎛ ⎞

⎜ 4 22 5 6 ⎟
⎜ ⎟
⎜ 7 23 8 9 ⎟
⎝ ⎠
10 24 11 12

Extract row 2:

m[]

(4, 5, 6)

Extract column 2

## m[[All, 2]] // MatrixForm

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 1/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
2
⎛ ⎞

⎜ 5 ⎟
⎜ ⎟
⎜ 8 ⎟

⎝ ⎠
11

## Insert a row at position 2:

v = Range[13, 15];
Insert[m, v, 2] // MatrixForm

1 2 3
⎛ ⎞

⎜ 13 14 15 ⎟
⎜ ⎟
⎜ ⎟
⎜ 4 5 6 ⎟
⎜ ⎟
⎜ 7 8 9 ⎟
⎝ ⎠
10 11 12

## column 3 = column 3 + column 1:

m2 = m;
m2[[All, 3]] += m2[[All, 1]];
m2 // MatrixForm

1 2 4
⎛ ⎞

⎜ 4 5 10 ⎟
⎜ ⎟
⎜ 7 8 16 ⎟
⎝ ⎠
10 11 22

## row 2 = row 2 + row 3:

m2 = m;
m2[] += m2[];
m2 // MatrixForm

1 2 3
⎛ ⎞

⎜ 11 13 15 ⎟
⎜ ⎟
⎜ 7 8 9 ⎟
⎝ ⎠
10 11 12

## Swap row 1 and row 3:

m2 = m;
m2[[{1, 3}]] = m2[[{3, 1}]];
m2 // MatrixForm

7 8 9
⎛ ⎞

⎜ 4 5 6 ⎟
⎜ ⎟
⎜ 1 2 3 ⎟
⎝ ⎠
10 11 12

m2 // MatrixForm

3 2 1
⎛ ⎞

⎜ 6 5 4 ⎟
⎜ ⎟
⎜ 9 8 7 ⎟
⎝ ⎠
12 11 10

## Multiply row 2 with 2:

m*{1, 2, 1, 1} // MatrixForm

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 2/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
1 2 3
⎛ ⎞

⎜ 8 10 12 ⎟
⎜ ⎟
⎜ 7 8 9 ⎟
⎝ ⎠
10 11 12

## ((m // Transpose)*{5, 1, 1}) // Transpose // MatrixForm

5 2 3
⎛ ⎞

⎜ 20 5 6 ⎟
⎜ ⎟
⎜ 35 8 9 ⎟
⎝ ⎠
50 11 12

References

What is the most efficient way to add rows and columns to a matrix?
Thanks to nikie for suggesting Matrix and Tensor Operations tutorial
Chris Degnen pointed out https://stackoverflow.com/questions/7537401/how-to-insert-a-column-into-a-matrix-the-correct-mathematica-
way

## edited May 23 '17 at 12:35 asked Mar 16 '12 at 8:23

Community ♦ sjdh
1 3,144 5 24 41

4 you don t need All` to get a row. m[] and m[[2,All]] both give the second row of m . – kglr Mar 16 '12 at
8:37

What about a partial column, say column one and first three rows, say using your example to get 1, 4, 7? I tried
mat[[{1, 3}, 1]] // MatrixForm -> {1},{7}, but I want {1},{4},{7}? – sebastian c. Jan 15 '13 at 16:54

ok got it, need to Transpose, Flatten, Take as in: Take[Flatten[Transpose[mat]], {1, 3}] -> {1,4,7}, unless there are
betters way to do so? – sebastian c. Jan 15 '13 at 17:16

## 1 How about deleting a row or column? – Hirek Feb 28 '15 at 19:00

2 @Hirek, you'll want to look up Drop[] and Delete[] . – J. M. ♦ Jun 18 '15 at 9:35

I like to use Part even when I don't want to modify the original matrix. This of course requires
making a copy but it keeps syntax more consistent.

## adding column one to column three:

m = Range@12 ~Partition~ 3;
m // MatrixForm

1 2 3
⎛ ⎞

⎜ 4 5 6 ⎟
⎜ ⎟
⎜ 7 8 9 ⎟
⎝ ⎠
10 11 12

m2 = m;

m2 // MatrixForm

1 2 4
⎛ ⎞

⎜ 4 5 10 ⎟
⎜ ⎟
⎜ 7 8 16 ⎟
⎝ ⎠
10 11 22

## v = {-1, -2, -3, -4};

m2 = m;

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 3/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
m2[[All, 3]] += v;

m2 // MatrixForm

1 2 2
⎛ ⎞

⎜ 4 5 4⎟
⎜ ⎟
⎜ 7 8 6⎟
⎝ ⎠
10 11 8

m2 = m;

m2 // MatrixForm

7 8 9
⎛ ⎞

⎜ 4 5 6 ⎟
⎜ ⎟
⎜ 1 2 3 ⎟
⎝ ⎠
10 11 12

m2 = m;

m2 // MatrixForm

3 2 1
⎛ ⎞

⎜ 6 5 4 ⎟
⎜ ⎟
⎜ 9 8 7 ⎟
⎝ ⎠
12 11 10

m2 = m;

## m2[[3 ;;, 2 ;;]] /= 5;

m2 // MatrixForm

1 2 3
⎛ ⎞

⎜ 4 5 6 ⎟
⎜ ⎟
⎜ 8 9 ⎟
7
⎜ 5 5 ⎟

⎝ 11 12 ⎠
10
5 5

Or a disjoint specification:

m2 = m;

m2 // MatrixForm

0 2 0
⎛ ⎞

⎜ 0 5 0⎟
⎜ ⎟
⎜ 7 8 9⎟
⎝ ⎠
0 11 0

## Or construct a new array from constituent parts in arbitrary order:

mx = BoxMatrix - 1;

## mx[[{1, 2, 5, 4}, {4, 5, 1}]] = m;

mx // MatrixForm

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 4/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
3 0 0 1 2
⎛ ⎞

⎜ 6 0 0 4 5 ⎟
⎜ ⎟
⎜ ⎟
⎜ 0 0 0 0 0 ⎟
⎜ ⎟
⎜ 12 0 0 10 11 ⎟
⎝ ⎠
9 0 0 7 8

## edited Jul 16 '17 at 20:24 answered Mar 16 '12 at 9:38

Mr.Wizard ♦
221k 28 445 965

1 +1. Agreed: part is just so flexible and convenient it's often the nicest way to go about these. – Szabolcs Mar 17 '12
at 7:36

Just ask: Why won't the code m2[[All, {1, 3}]] = m2[[All, {3, 1}]]; just give column 1 and 3 indentical?
First you assign column 3 to column 1, then you assign column 1 to column 3, which has already become the original
column 3... – buzhidao Dec 29 '15 at 11:58

@buzhidao I don't know if I can explain this clearly for you since it seems I failed the first time. There is only a single
assignment in that expression, and only a single reversal of columns. It might be translated to "let columns 1 and 3
be set to columns 3 and 1". A simpler example without columns is a = {1, 2, 3, 4, 5}; then a[[{1, 3}]] =
a[[{3, 1}]]; after which a is {3, 2, 1, 4, 5} . – Mr.Wizard ♦ Dec 30 '15 at 0:10

@buzhidao Help on WhenEvent discusses something alike: sequential actions modify variables in turn, e.g. {x[t]
-> y[t], y[t] -> x[t]} , while simultaneous actions swap, e.g. {x[t], y[t]} -> {y[t], x[t]} . I think this
is idiomatic to the system. – BoLe Jul 30 '16 at 9:59

Interchanging rows

## Permute[mat, Cycles[{{1, 3}}]]

To swap columns, you can convert the permutation to a permutation list, and use

mat[[All, permList]]

Multiplying rows

mat[] *= 5

Szabolcs
142k 10 381 811

## For small matrices, using simple indexing might be more readable:

Interchanging rows:

m[[{1, 3, 2}]]

Multiplying rows:

m * {1,2,1}

m + {0,v,0}

For large matrices, you could use SparseArray to generate the second matrix (less readable,
but works for any matrix size and might be faster, too):

## m * SparseArray[2 -> 2, Length[m], 1]

m + SparseArray[2 -> v, Length[m], 0]

## Insert a row into a matrix

Insert[m, v, 2]

You might want to look at the Matrix and Tensor Operations tutorial, too
https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 5/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
edited Mar 16 '12 at 10:42 answered Mar 16 '12 at 10:12
Niki Estner
28k 3 65 122

For multiplying and adding rows---I agree it's likely the most efficient way. Can you show your preferred way to
generate those vectors ( {1,2,1} and {0,v,0} ) if the matrix is large? I miss a way equivalent to mat[] *= 2
which returns a copy instead of modifying the matrix. – Szabolcs Mar 16 '12 at 10:22

@Szabolcs: Isn't m * {1,2,1} the functional equivalent to mat[] *= 2 ? – Niki Estner Mar 16 '12 at 10:57

If it's a 10 by 10 matrix, and you want the 7th elements, you have to write {1,1,1,1,1,1,3,1,1,1} and make sure
that you inserted 3 in the correct position. This is tedious and error prone. This is why I asked how you prefer to
generate that vector. – Szabolcs Mar 16 '12 at 10:59

These are ancient routines I have been using a long time ago. As a matter of fact, it's been so
long that I do not even remember if I wrote them or simply shamelessly took them from some
other source. Back at the time the only sources I had at my disposal where The Mathematical
Journal (prior to 1998 or 1999), Bahder's wonderful book (which is the most likely source, at
least of inspiration, given the style), Mathematica By Example (first edition) by Abell and
Braselton and... Matlab for Engineers (LOL, I'm not kidding) by Biran and Breiner. The reason I
am not sure to be the author myself is because these procedures appear too smart for me to
have conceived them :-). If someone can trace the original source, I will give it due credit.

Main procedures:

row[A_,n_]:=A[[n]]
col[A_,n_]:=#[[n]]& /@ A
Col[A_,n_]:={#[[n]]}& /@ A

col returns the column in the form {x1,x2,...} Col returns it as {{x1},{x2},...} ("vertical"
vector)

Smart applying:

row /: (row[A_,n_]=r_):=(A[[n]]=r)
col /: (col[A_,n_]=c_):=(A[[ Range[Dimensions[A][]],{n} ]]=(List /@ c))
Col /: (Col[A_,n_]=c_):=(A[[ Range[Dimensions[A][]],{n} ]]=c)
row /: (row[A_,n_]:=r_):=(A[[n]]:=r)
col /: (col[A_,n_]:=c_):=(A[[ Range[Dimensions[A][]],{n} ]]:=(List /@ c))
Col /: (Col[A_,n_]:=c_):=(A[[ Range[Dimensions[A][]],{n} ]]:=c)

## Now... here is how to use them. Let's start with a matrix

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

Suppose you want to replace the second column of A with 100 times its value. All you need to
do is to tell Mathematica what is the new value of the column, for example 100 times its current
value:

col[A,2]=100*col[A,2]

{200,500,800}

The side effect of col is to show the new value of the column, but its primary and intended
effect is to change the original matrix A accordingly:

## { {1,200,3}, {4,500,6}, {7,800,9} }

row can be used in the same way. Suppose we want to substitute the first row with a linear
combination of all three rows of A

{2, 400, 6}

## The original matrix A is changed accordingly.

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 6/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange

## { {2,400,6}, {4,500,6}, {7,800,9} }

Basically these procedures allow one to do all the operations he or she wishes on rows and
columns of a matrix. Extracting, defining, substituting with linear combinations or whatever
comes to one's mind. As mentioned before, if one desires to extract a column in the form {{a},
{b},{c}} , he should use Col instead of col .

## Pretty col , uh?

EDIT: I just found a more elaborate notebook with "the making of" written by me where I refer
to "Thomas Bahder's MMA for Scientists and Engineers", "Bruce Ikenaga'a Matrix Operations"
and "me" as sources. So perhaps I was the author of the wrappers... Later this week I will add
the procedures for joining, inserting, appending and swapping rows and columns and I will try
to ascertain who wrote what.

Peltio
4,066 3 19 24

## Inserting columns (recycling answers from here).

m = Range@12~Partition~3;
m // MatrixForm
v = Range[21, 24];

## edited May 23 '17 at 12:35 answered Mar 16 '12 at 16:16

Community ♦ Chris Degnen
1 19.6k 2 30 73

How to put this numbers in index, for example A1,A2,A3,A4..A12? m = Range@12 ~Partition~ 3; m // MatrixForm –
George Mills Apr 16 '12 at 14:14

Do you mean like this? Clear[A]; Print[ MatrixForm[m = Outer[A, {1, 2, 3, 4}, {1, 2, 3}]]]; v =
Range[21, 24]; MapThread[Insert, {m, v, Table[2, {Length[v]}]}] // MatrixForm – Chris Degnen Apr
16 '12 at 18:45

## Or perhaps like this: Print[MatrixForm[m = Range@12~Partition~3]]; Clear[A]; Print[ v = Array[A,

4]]; MapThread[Insert, {m, v, Table[2, {Length[v]}]}] // MatrixForm – Chris Degnen Apr 17 '12 at
8:15

Do we have to build Table[2, {Length[v]}] ? IMO MapThread[Insert[#1, #2, 2] &, {m, v}] is cleaner. –
Yi Wang Apr 15 '14 at 13:01

1 It's just an alternative form. I prefer MapThread too, although now I have seen another method from Kuba: Efficient
method for Inserting arrays into arrays. – Chris Degnen Apr 15 '14 at 13:07

Not as simple as the other solutions, but the linear-algebraic treatment might be convenient in
some applications:

m = Partition[Range, 3];

## answered Jun 22 '12 at 10:05

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 7/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
J. M. ♦
84.7k 9 268 403

This "replace" methods work only if there are no repeated rows (or columns if you will
generalize) - see comments. For more general approach see @Szabolcs solution.

m // MatrixForm

## m /. m[] -> m[] + m[] // MatrixForm

Interchanging rows

Multiplying row

## m /. {m[] -> 3 m[]} // MatrixForm

Subtracting columns

## Transpose@m /. {m[[All, 2]] -> m[[All, 2]] - m[[All, 1]]}

//Transpose // MatrixForm

## edited Mar 16 '12 at 9:42 answered Mar 16 '12 at 8:38

Vitaliy Kaurov
53.1k 6 149 259

With adding rows, I mean adding the numbers of one row to an existing row – sjdh Mar 16 '12 at 8:59

What if the matrix has two rows that are the same? The Replace approach will affect both. – Szabolcs Mar 16 '12
at 9:09

## @sjdh I see - added an example. – Vitaliy Kaurov Mar 16 '12 at 9:09

4 These ReplaceAll methods are dangerous because a matrix may contain repeated rows or columns. –
Mr.Wizard ♦ Mar 16 '12 at 9:10

@Szabolcs (and Mr.Wizard and nikie ;-) ) Very true - I'll add a comment at the top. – Vitaliy Kaurov Mar 16 '12 at 9:13

There are some internal, undocumented functions for row and columns operations:

## (* in-place(!) transformation of the matrix *)

Statistics`Library`MatrixRowTranslate[matrix, vector]

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 8/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
Statistics`Library`MatrixRowTimes[matrix, vector]
Statistics`Library`MatrixRowAffineTransform[matrix, vector, vector] (* mat, times, xlate
*)
Statistics`Library`MatrixRowAffineTransform[matrix, scalar, vector]
(* returns vector *)
Statistics`Library`MatrixColumnSum[matrix]
Statistics`Library`MatrixRowSum[matrix]

The first four have the inelegance, admittedly, of modifying the argument matrix in place, and
so are not well-suited for functional programming. On the other hand, all six are efficient,
especially on numeric arrays, packed or unpacked. Perhaps the OP's original scope does not
comprise all these operations, although it is somewhat open-ended; however, I thought that
since they are strongly related, it would be better to have them all here than in a separate
Q&A.

Note that a vector argument can easily be a row or column of matrix , but the whole matrix
will be transformed in those cases.

Examples

mm = {
{a, b, c},
{d, e, f},
{g, h, i},
{j, k, l}
};

## Add a vector to each row:

Module[{res = mm},
Statistics`Library`MatrixRowTranslate[res, {u, v, w}];
res] // MatrixForm

Multiply each row by a vector: It's elementwise scalar multiplication, the same as row *
vector , for each row in the matrix.

Module[{res = mm},
Statistics`Library`MatrixRowTimes[res, {x, y, z}];
res] // MatrixForm

Multiply each column by a vector: Times already does what the missing
MatrixColumnTimes[] would do:

mm*{w, x, y, z} // MatrixForm

## Affine transformation of the rows: The MatrixRowAffineTransform can be viewed as

multiplying the row by {x, y, z}] and adding the second vector {u, v, w} , or as operating on
the columns threading the components of the vectors.

Module[{res = mm},
Statistics`Library`MatrixRowAffineTransform[res, {x, y, z}, {u, v, w}];
res] // MatrixForm

## MatrixRowAffineTransform allows the scaling argument to be a scalar.

Module[{res = mm},
Statistics`Library`MatrixRowAffineTransform[res, x, {u, v, w}];
res] // MatrixForm

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 9/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange

Affine transformation of the columns: Again, Times and Plus supply the missing
MatrixColumnAffineTransform[] :

## Summing rows or columns:

Statistics`Library`MatrixColumnSum[mm]
(* {a + d + g + j, b + e + h + k, c + f + i + l} *)

Statistics`Library`MatrixRowSum[mm]
(* {a + b + c, d + e + f, g + h + i, j + k + l} *)

Timings of the sums can be found here. Since the OP explicitly said speed was not an issue, I
didn't want to clutter this post with timings. Nonetheless, these are, as I mentioned, fast on
numeric arrays.

## edited Jul 2 '17 at 17:08 answered Jul 2 '17 at 0:10

Michael E2
129k 11 175 419

3 (+1) In which version these functions were introduced? They aren't present in version 8.0.4. (Also you forgot to add
the link in the last paragraph.) – Alexey Popkov Jul 2 '17 at 9:24

I think in V10. I don't have access to all past versions, but they're in V10.4.1. – Michael E2 Jul 2 '17 at 17:06

As matrix multiplication is highly optimized (see here), Dot and Inner (the general form of Dot)
are often very efficient methods for column manipulation.

## (m = Array[Subscript[a, ##] &, {2, 3}]) // MatrixForm

v = Table[Subscript[x, i], {i, 1, 3}]

## a 1,1 a 1,2 a 1,3

( )
a 2,1 a 2,2 a 2,3

{x1 , x2 , x3 }

## Often it is not the dot product that is of interest,

m.v // MatrixForm

## {x1 a 1,1 + x2 a 1,2 + x3 a 1,3 , x1 a 2,1 + x2 a 2,2 + x3 a 2,3 }

but

(m.DiagonalMatrix[v])//MatrixForm

## x1 a 1,1 x2 a 1,2 x3 a 1,3

( )
x1 a 2,1 x2 a 2,2 x3 a 2,3

## Inner gives the same result:

Inner[Times, m, DiagonalMatrix[v]]

In the general form, Inner[f,list1,list2,g] , 'f plays the role of multiplication and g of addition'
(Inner), and the result may also be obtained with:

Inner[Times, m, v, List]

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 10/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
That is:

## Multiply a Column by a Factor

(See Change entire column of matrix using its own elements for calculations)

Multiply column-4 by 10

## a 1,1 a 1,2 10a 1,3

( )
a 2,1 a 2,2 10a 2,3

The diagonal matrix may be generated more efficiently with SparseArray. This gives the same
result:

Using Inner:

or:

a 1,1 0 0
( )
a 2,1 0 0

Alternatively:

## a 1,1 + a 1,3 a 1,2 a 1,3

( )
a 2,1 + a 2,3 a 2,2 a 2,3

For clarity:

1 0 0
⎛ ⎞

⎜ 0 1 0⎟
⎝ ⎠
1 0 1

## Subtract Column-3 from Column-2

m // #.SparseArray[{{3, 2} -> -1, Band[{1, 1}] -> 1}, Dimensions[#][]] & // MatrixForm

## a 1,1 a 1,2 − a 1,3 a 1,3

( )
a 2,1 a 2,2 − a 2,3 a 2,3

## Subtract Column-1 from all other Columns

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 11/12
1/29/2018 list manipulation - Elegant operations on matrix rows and columns - Mathematica Stack Exchange
See the answer by Carl Woll to Subtracting elements in a nested list

MatrixForm

## a 1,1 a 1,2 − a 1,1 a 1,3 − a 1,1

( )
a 2,1 a 2,2 − a 2,1 a 2,3 − a 2,1

## edited Jun 11 '17 at 19:54 answered Jun 7 '17 at 14:52

tomd
5,343 2 17 30

https://mathematica.stackexchange.com/questions/3069/elegant-operations-on-matrix-rows-and-columns 12/12