This is documentation for Mathematica 5, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)

Documentation / Mathematica / The Mathematica Book / Advanced Mathematics in Mathematica / Linear Algebra /

3.7.12 Sparse Arrays

Many large-scale applications of linear algebra involve matrices that have many elements, but comparatively few that are non-zero. You can represent such sparse matrices efficiently in Mathematica using SparseArray objects, as discussed in Section 2.4.5. SparseArray objects work by having lists of rules that specify where non-zero values appear.

Specifying sparse arrays.

As discussed in Section 2.4.5, 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 sparse numerical matrix, with 148 non-zero elements.

In[1]:= m = SparseArray[{{30, _} -> 11.5, {_, 30} -> 21.5,
{i_, i_} -> i}, {50, 50}]


This shows a visual representation of the matrix elements.

In[2]:= ListDensityPlot[-m]


Here are the four largest eigenvalues of the matrix.

In[3]:= Eigenvalues[m, 4]


Dot gives a SparseArray result.

In[4]:= m . m


You can extract parts just like in an ordinary array.

In[5]:= %[[20, 20]]


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.

A few structural operations that can be done directly on SparseArray objects.

This gives the first column of m. It has only 2 non-zero elements.

In[6]:= m[[All, 1]]


This adds 3 to each element in the first column of m.

In[7]:= m[[All, 1]] = 3 + m[[All, 1]]


Now all the elements in the first column are non-zero.

In[8]:= m[[All, 1]]


This gives the rules for the non-zero elements on the second row.

In[9]:= ArrayRules[m[[2]]]


Typical ways to get sparse arrays.

This generates a tridiagonal random matrix.

In[10]:= SparseArray[{i_, j_} /; Abs[i-j] <= 1 :> Random[],
{100, 100}]


Even the tenth power of the matrix is still fairly sparse.

In[11]:= MatrixPower[%, 10]


This extracts the coefficients as sparse arrays.

In[12]:= s = CoefficientArrays[{c + x - z == 0, x + 2 y + z == 0},
{x, y, z}]


Here are the corresponding ordinary arrays.

In[13]:= Normal[%]


This reproduces the original forms.

In[14]:= s[[1]] + s[[2]] . {x, y, z}


CoefficientArrays can handle general polynomial equations.

In[15]:= s = CoefficientArrays[
{c + x^2 - z == 0, x^2 + 2 y + z^2 == 0},
{x, y, z}]


The coefficients of the quadratic part are given in a rank 3 tensor.

In[16]:= Normal[%]


This reproduces the original forms.

In[17]:= s[[1]] + s[[2]] . {x, y, z} + s[[3]] . {x, y, z} . {x, y, z}


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.