How to | Work with Sparse Matrices
Sparse representations of matrices are useful because they do not store every element. If one particular value appears very frequently it can be very advantageous to use a sparse representation.
Mathematica offers a sparse representation for matrices, vectors, and tensors with
SparseArray. These are very closely related to dense matrices, which are represented by lists. Most operations that work for lists also work for sparse arrays.
There are a number of ways to create sparse arrays. Many of them make use of the function
SparseArray.
This creates a sparse matrix from a dense matrix. The sparse matrix does not print like a matrix because it might be extremely large:
| Out[1]= |  |
You can still format the matrix like a matrix:
Out[2]//MatrixForm= |
| |  |
This creates a sparse matrix by specifying the elements that are nonzero:
| Out[3]= |  |
You can also use the rule syntax
:> with
Mathematica patterns to create structured sparse matrices. This example makes a tridiagonal matrix:
Out[4]//MatrixForm= |
| |  |
More complicated matrices can be made with
Band. In this example a band is created along the antidiagonal:
Out[5]//MatrixForm= |
| |  |
You can also create sparse matrices by importing one of the sparse matrix formats such as Harwell-Boeing or Matrix Market.
This imports a sample 961×961 matrix that has 10591 nonzero elements:
| Out[6]= |  |
Functions that work with dense matrices typically work with sparse matrices. Often they will use special sparse matrix techniques that are faster and work without ever converting to a dense matrix. This leads to large savings of time and memory.
This creates a banded sparse matrix:
| Out[7]= |  |
Out[8]//MatrixForm= |
| |  |
When a sparse matrix is multiplied by itself the result is also a sparse matrix, but the number of zero elements might not be as optimal as before:
| Out[9]= |  |
This is the result; you can see that the number of zero elements has reduced:
Out[10]//MatrixForm= |
| |  |
You can extract and set elements of sparse matrices just as you do with dense matrices:
| Out[11]= |  |
This extracts element (2, 3):
| Out[12]= |  |
This sets element (2, 3) to be 20:
Out[13]//MatrixForm= |
| |  |
Sometimes it is useful to get a view of the location of the nonzero elements in a sparse matrix. This can be done with
MatrixPlot. Even if the matrix has many elements,
MatrixPlot provides an efficient view of the sparsity pattern of a matrix.
This loads a large matrix with
Import:
| Out[14]= |  |
Now the matrix is plotted, showing that there is quite a degree of structure to the matrix:
| Out[15]= |  |