Sparse Arrays: Linear Algebra
Many large-scale applications of linear algebra involve matrices that have many elements, but comparatively few that are nonzero. You can represent such sparse matrices efficiently in Mathematica using SparseArray objects, as discussed in "Sparse Arrays: Manipulating Lists". SparseArray objects work by having lists of rules that specify where nonzero values appear.
| SparseArray[list] | a SparseArray version of an ordinary list |
| SparseArray[{{i1,j1}->v1,{i2,j2}->v2,...},{m,n}] |
| an m×n sparse array with element having value  |
| SparseArray[{{i1,j1},{i2,j2},...}->{v1,v2,...},{m,n}] |
| the same sparse array |
| Normal[array] | the ordinary list corresponding to a SparseArray |
Specifying sparse arrays.
As discussed in "Sparse Arrays: Manipulating Lists", you can use patterns to specify collections of elements in sparse arrays. You can also have sparse arrays that correspond to tensors of any rank.
This makes a 50×50 sparse numerical matrix, with 148 nonzero elements.
| Out[1]= |  |
This shows a visual representation of the matrix elements.
| Out[2]= |  |
Here are the four largest eigenvalues of the matrix.
| Out[3]= |  |
| Out[4]= |  |
You can extract parts just like in an ordinary array.
| Out[5]= |  |
You can apply most standard structural operations directly to SparseArray objects, just as you would to ordinary lists. When the results are sparse, they typically return SparseArray objects.
| Dimensions[m] | the dimensions of an array |
| ArrayRules[m] | the rules for nonzero elements in an array |
| m[[i,j]] | element i, j |
| m[[i]] | the i row |
| m[[All,j]] | the j column |
| m[[i,j]]=v | reset element i, j |
A few structural operations that can be done directly on SparseArray objects.
This gives the first column of

. It has only 2 nonzero elements.
| Out[6]= |  |
This adds 3 to each element in the first column of

.
| Out[7]= |  |
Now all the elements in the first column are nonzero.
| Out[8]= |  |
This gives the rules for the nonzero elements on the second row.
| Out[9]= |  |
| SparseArray[rules] | generate a sparse array from rules |
| CoefficientArrays[{eqns1,eqns2,...},{x1,x2,...}] |
| get arrays of coefficients from equations |
| Import["file.mtx"] | import a sparse array from a file |
Typical ways to get sparse arrays.
This generates a tridiagonal random matrix.
| Out[10]= |  |
Even the tenth power of the matrix is still fairly sparse.
| Out[11]= |  |
This extracts the coefficients as sparse arrays.
| Out[12]= |  |
Here are the corresponding ordinary arrays.
| Out[13]= |  |
This reproduces the original forms.
| Out[14]= |  |
| Out[15]= |  |
The coefficients of the quadratic part are given in a rank 3 tensor.
| Out[16]= |  |
This reproduces the original forms.
| Out[17]= |  |
For machine-precision numerical sparse matrices, Mathematica supports standard file formats such as Matrix Market (.mtx) and Harwell-Boeing. You can import and export matrices in these formats using Import and Export.