Getting Pieces of MatricesExtracting elements, rows, and columns of a sparse matrix is quite straightforward with the Mathematica function Part. Typically Part is entered with [[ ]] notation. Ways to get pieces of matrices. Here is a sample sparse matrix. In[1]:=  |
Out[2]//MatrixForm=
|
This gets the third element in the first row. In[3]:=  |
Out[3]=
|
This gets the third row; the row is returned as a sparse vector. In[4]:=  |
Out[4]=
|
It can also obtain a column by using All to specify all rows; the column is returned as a sparse vector. In[5]:=  |
Out[5]=
|
Negative indices are used to refer to the end of the matrix. The following gets the last element of the last row. In[6]:=  |
Out[6]=
|
The function Tr works on the diagonal elements of a matrix. The one argument form adds them up. In[7]:=  |
Out[7]=
|
Tr can also take a function as its second argument, which will apply to the diagonal elements. If List is used, this returns the diagonal elements. In[8]:=  |
Out[8]=
|
Getting Multiple PiecesIt is possible to extract multiple elements by using indices in lists. This will be demonstrated with the following sample matrix. In[1]:=  |
Out[2]//MatrixForm=
|
The following gets the first and third elements of the third row. In[3]:=  |
Out[3]=
|
The following gets the first and third rows. In[4]:=  |
Out[4]=
|
The following gets the first and third elements of the first and second rows. In[5]:=  |
Out[5]=
|
|