Mathematica 9 is now available
Previous section-----Next section

3.7.2 Getting and Setting Pieces of Matrices

m[[i, j]] the   entry
m[[i]] the   row
m[[All, i]] the   column
Take[m, { ,  }, { ,  }] the submatrix with rows  through  and columns  through
m[[{ , ... ,  }, { , ... ,  }]] the  submatrix with elements having row indices  and column indices
Tr[m, List] elements on the diagonal
ArrayRules[m] positions of non-zero elements

Ways to get pieces of matrices.

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

Here is a sample  matrix.

In[1]:=  t = Array[a, {3, 3}]

Out[1]=

This picks out the second row of the matrix.

In[2]:=  t[[2]]

Out[2]=

Here is the second column of the matrix.

In[3]:=  t[[All, 2]]

Out[3]=

This picks out a submatrix.

In[4]:=  Take[t, {1, 2}, {2, 3}]

Out[4]=

m = {{ ,  , ... }, { ,  , ... }, ... }
assign m to be a matrix
m[[i, j]] = v reset element {i, j} to be v
m[[i]] = v reset all elements in row i to be v
m[[i]] = { ,  , ... } reset elements in row i to be { ,  , ... }
m[[All, j]] = v reset all elements in column j to be v
m[[All, j]] = { ,  , ... } reset elements in column j to be { ,  , ... }

Resetting parts of matrices.
Here is a  matrix.

In[5]:=  m = {{a, b}, {c, d}}

Out[5]=

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

In[6]:=  m[[2, 2]] = x; m

Out[6]=

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

In[7]:=  m[[All, 2]] = z; m

Out[7]=

This separately resets the two elements in the second column.

In[8]:=  m[[All, 2]] = {i, j}; m

Out[8]=

This increments all the values in the second column.

In[9]:=  m[[All, 2]]++; m

Out[9]=



Any questions about topics on this page? Click here to get an individual response.Buy NowMore Information
THIS IS DOCUMENTATION FOR AN OBSOLETE PRODUCT.
SEE THE DOCUMENTATION CENTER FOR THE LATEST INFORMATION.