Search⌘ K

Sparse Matrices

Explore how to create, convert, and manipulate sparse matrices in Python with SciPy's sparse submodule. Understand efficient storage formats like compressed sparse row and column, and learn to solve systems of linear equations using sparse matrix methods to optimize scientific computations.

Sparse matrices in Python #

The procedure we have used so far to construct the matrix for a is not very efficient. A full matrix is created, which consists mostly of zeros with non-zero values only appearing on diagonals. There are more efficient routines that store what are called sparse matrices. In a sparse matrix, only the value and location of non-zero values in a matrix are stored. Functionality for sparse matrices is available in the scipy submodule sparse.

We will import the scipy.sparse submodule as sp.

import scipy.sparse as sp

Dense to sparse #

When we create a sparse matrix, we have to choose which format it should be stored in. There are many ways to store a sparse matrix. Two most commonly used are:

  1. compressed sparse column using the csc_matrix(A) method.
  2. compressed sparse row using the csr_matrix(A) method.

The following matrix is an example of this:

[230012 ...