TExcelTAD
Home › Numerical Methods › Banded and Symmetric Positive Definite Matrices

Banded and Positive Definite Matrices

The matrices that come out of applications are rarely arbitrary. Discretized differential equations give banded matrices with nonzeros only near the diagonal; least squares, statistics and energy methods give symmetric positive definite (SPD) matrices. Exploiting this structure cuts the cost of a solve from O(n3)O(n^3) to as little as O(n)O(n), and removes the need for pivoting.

Banded matrices

AA has bandwidth pp (lower) and qq (upper) if aij=0a_{ij} = 0 whenever i−j>pi - j > p or j−i>qj - i > q. LU without pivoting keeps the band: LL has lower bandwidth pp and UU upper bandwidth qq, and the cost is O(npq)O(npq). A tridiagonal matrix (p=q=1p = q = 1) is solved in O(n)O(n) by the Thomas algorithm:

python · try it yourself
import numpy as np
from scipy.linalg import solve_banded

def thomas(a, d, c, b):
    """Solve a tridiagonal system: sub-diagonal a, diagonal d, super-diagonal c."""
    n = len(d)
    d = d.astype(float).copy(); b = b.astype(float).copy()
    for i in range(1, n):
        m = a[i - 1] / d[i - 1]
        d[i] -= m * c[i - 1]
        b[i] -= m * b[i - 1]
    x = np.zeros(n)
    x[-1] = b[-1] / d[-1]
    for i in range(n - 2, -1, -1):
        x[i] = (b[i] - c[i] * x[i + 1]) / d[i]
    return x

n = 8
a = -np.ones(n - 1); c = -np.ones(n - 1); d = 2.0 * np.ones(n)   # the 1D Laplacian
b = np.ones(n)
x = thomas(a, d, c, b)
ab = np.vstack([np.r_[0, c], d, np.r_[a, 0]])                     # LAPACK banded storage
print("Thomas     :", np.round(x, 6))
print("solve_banded:", np.round(solve_banded((1, 1), ab, b), 6))
Thomas     : [ 4.  7.  9. 10. 10.  9.  7.  4.]
solve_banded: [ 4.  7.  9. 10. 10.  9.  7.  4.]

The matrix tridiag⁡(−1,2,−1)\operatorname{tridiag}(-1, 2, -1) appears in Finite Differences for BVPs and the heat equation.

Symmetric positive definite matrices

AA is SPD if A=ATA = A^T and xTAx>0\mathbf{x}^TA\mathbf{x} > 0 for all x≠0\mathbf{x} \ne \mathbf{0}. Equivalent tests: all eigenvalues are positive; all pivots of elimination are positive. Examples: covariance matrices, BTBB^TB with BB of full column rank, stiffness matrices, Hessians at a strict minimum.

Cholesky factorization

Every SPD matrix factors as

A=RTR,A = R^TR,

with RR upper triangular with positive diagonal (equivalently A=LLTA = LL^T). It costs 13n3\frac{1}{3}n^3 flops, half of LU, needs no pivoting, and is unconditionally backward stable. Failure of Cholesky (a non-positive value under a square root) is the standard numerical test for positive definiteness.

python · try it yourself
import numpy as np

def cholesky(A):
    n = A.shape[0]
    R = np.zeros_like(A, dtype=float)
    for k in range(n):
        s = A[k, k] - R[:k, k] @ R[:k, k]
        if s <= 0:
            raise np.linalg.LinAlgError("matrix is not positive definite")
        R[k, k] = np.sqrt(s)
        R[k, k + 1:] = (A[k, k + 1:] - R[:k, k] @ R[:k, k + 1:]) / R[k, k]
    return R

A = np.array([[4.0, 2, -2], [2, 10, 4], [-2, 4, 9]])
R = cholesky(A)
print("R =\n", R)
print("R^T R == A:", np.allclose(R.T @ R, A), "| NumPy L == R^T:", np.allclose(np.linalg.cholesky(A), R.T))
try:
    cholesky(np.array([[1.0, 2], [2, 1]]))
except np.linalg.LinAlgError as e:
    print("[[1, 2], [2, 1]]:", e)
R =
 [[ 2.          1.         -1.        ]
 [ 0.          3.          1.66666667]
 [ 0.          0.          2.2852182 ]]
R^T R == A: True | NumPy L == R^T: True
[[1, 2], [2, 1]]: matrix is not positive definite

Sampling with Cholesky

If z\mathbf{z} has independent standard normal entries and Σ=LLT\Sigma = LL^T, then LzL\mathbf{z} has covariance Σ\Sigma. This is how multivariate normal samples are generated:

python · try it yourself
import numpy as np

Sigma = np.array([[1.0, 0.8], [0.8, 2.0]])
L = np.linalg.cholesky(Sigma)
rng = np.random.default_rng(12)
Z = rng.standard_normal((2, 200_000))
X = L @ Z
print("sample covariance:\n", np.round(np.cov(X), 3))
sample covariance:
 [[1.    0.794]
 [0.794 1.993]]

In software

  • scipy.linalg.cho_factor / cho_solve for SPD systems; scipy.linalg.solve(A, b, assume_a="pos") picks Cholesky; solve_banded and solveh_banded for banded matrices.
  • Gaussian processes, Kalman filters and Newton's method for convex problems all run on Cholesky factorizations.

Exercises

Exercise 1: Tridiagonal cost

How many flops does the Thomas algorithm take, to leading order?

Answer

About 8n8n.

Solution

Elimination: 1 division, 2 multiplications and 2 subtractions per row (5n5n); back substitution: about 3n3n. That is O(n)O(n), compared with 23n3\frac{2}{3}n^3 for dense LU.

Exercise 2: Is it SPD?

Is (2334)\begin{pmatrix} 2 & 3 \\ 3 & 4\end{pmatrix} positive definite?

Answer

No.

Solution

Elimination gives pivots 22 and 4−92=−12<04 - \frac{9}{2} = -\frac{1}{2} < 0 (equivalently det⁡=−1<0\det = -1 < 0).

Exercise 3: Cholesky versus LU (code)

For a random SPD matrix A=BTB+IA = B^TB + I with n=300n = 300, compare the solutions of cho_solve and np.linalg.solve and confirm they agree.

Answer

They agree to a relative difference of a few times 10−1410^{-14}, consistent with κ(A) u\kappa(A)\,u.

Solution
python · try it yourself
import numpy as np
from scipy.linalg import cho_factor, cho_solve
rng = np.random.default_rng(9)
B = rng.normal(size=(300, 300)); A = B.T @ B + np.eye(300); b = rng.normal(size=300)
x1 = cho_solve(cho_factor(A), b); x2 = np.linalg.solve(A, b)
print(f"{np.linalg.norm(x1 - x2) / np.linalg.norm(x2):.1e}")
3.4e-14

Test yourself

Cholesky factorization applies to…

  1. any square matrix
  2. symmetric positive definite matrices
  3. triangular matrices
  4. singular matrices

Solving a tridiagonal system costs…

  1. O(n3)O(n^3)
  2. O(n2)O(n^2)
  3. O(n)O(n)
  4. O(log⁡n)O(\log n)

Compared with LU, Cholesky costs about…

  1. twice as much
  2. the same
  3. half as much
  4. a tenth