typestar

Sparse matrices in Python

When most entries are zero, store only the ones that are not.

import numpy as np
from scipy import sparse
from scipy.sparse import linalg as splinalg

dense = np.array([[4.0, 0.0, 1.0], [0.0, 3.0, 0.0], [1.0, 0.0, 2.0]])
matrix = sparse.csr_array(dense)

print(matrix.shape, matrix.nnz, f"{matrix.nnz / dense.size:.0%} filled")
print(matrix.toarray()[0])

x = splinalg.spsolve(matrix.tocsc(), np.array([1.0, 2.0, 3.0]))
print(x.round(4), np.allclose(dense @ x, [1, 2, 3]))

identity = sparse.eye_array(3, format="csr")
print((matrix + identity).diagonal())

How it works

  1. csr_array is the row-oriented format for arithmetic and solving.
  2. nnz and toarray show what is stored against what it means.
  3. spsolve solves a sparse system without densifying it.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
494
Tokens
170
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 93 seconds.

Type this snippet

Step 1 of 4 in Sparse & spatial, step 19 of 23 in Scientific computing with SciPy.

← Previous Next →