# 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. The Wolfram Language 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:

In[1]:= |

Out[1]= |

You can still format the matrix like a matrix:

In[2]:= |

Out[2]//MatrixForm= | |

This creates a sparse matrix by specifying the elements that are nonzero:

In[3]:= |

Out[3]= |

You can also use the rule syntax with Wolfram Language patterns to create structured sparse matrices. This example makes a tridiagonal matrix:

In[4]:= |

Out[4]//MatrixForm= | |

More complicated matrices can be made with Band. In this example, a band is created along the antidiagonal:

In[5]:= |

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:

In[6]:= |

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:

In[1]:= |

Out[1]= |

In[2]:= |

Out[2]//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:

In[3]:= |

Out[3]= |

This is the result; you can see that the number of zero elements has reduced:

In[4]:= |

Out[4]//MatrixForm= | |

You can extract and set elements of sparse matrices just as you do with dense matrices:

In[1]:= |

Out[1]= |

In[2]:= |

Out[2]= |

This sets element (2, 3) to be 20:

In[3]:= |

Out[3]//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:

In[1]:= |

Out[1]= |

Now the matrix is plotted, showing that there is quite a degree of structure to the matrix:

In[2]:= |

Out[2]= |