Getting and Setting Pieces of Matrices

Ways to get pieces of matrices.

Matrices in the Wolfram Language are represented as lists of lists. You can use all the standard Wolfram Language list-manipulation operations on matrices.

Here is a sample 3×3 matrix:

t=Array[a,{3,3}]

This picks out the second row of the matrix:

t[[2]]

Here is the second column of the matrix:

t[[All,2]]

This picks out a submatrix:

Take[t,{1,2},{2,3}]

Resetting parts of matrices.

Here is a 3×3 matrix:

m={{a,b,c},{d,e,f},{g,h,i}}

This resets the 2, 2 element to be x, then shows the whole matrix:

m[[2,2]]=x;m

This resets all elements in the second column to be z:

m[[All,2]]=z;m

This separately resets the three elements in the second column:

m[[All,2]]={i,j,k};m

This increments all the values in the second column:

m[[All,2]]++;m

A range of indices can be specified by using ;; ((RefLink[Span, paclet:ref/Span])).

This resets the first two rows to be new vectors:

m[[1;;2]]={{u,v,w},{x,y,z}};m

This resets elements in the first and third columns of each row:

m[[All,1;;3;;2]]={{1,2},{3,4},{5,6}};m

This resets elements in the first and third columns of rows 2 through 3:

m[[2;;3,1;;3;;2]]={{a,b},{c,d}};m