TExcelTAD
Home › Numerical Methods › LU Factorization

LU Factorization

Gaussian elimination, the method taught in every linear algebra course, is really a matrix factorization: it writes A=LUA = LU with LL unit lower triangular and UU upper triangular. Separating the factorization from the solve is what makes it efficient: factor once in O(n3)O(n^3), then solve for any number of right-hand sides in O(n2)O(n^2) each.

Elimination as a factorization

Elimination subtracts multiples ℓik=aikakk\ell_{ik} = \frac{a_{ik}}{a_{kk}} of row kk from rows i>ki > k to create zeros below the pivot akka_{kk}. Collect the multipliers in a lower triangular matrix with ones on the diagonal: that is LL. What remains of AA is UU.

python · try it yourself
import numpy as np

def lu_nopivot(A):
    n = A.shape[0]
    U = A.astype(float).copy()
    L = np.eye(n)
    for k in range(n - 1):
        for i in range(k + 1, n):
            L[i, k] = U[i, k] / U[k, k]          # multiplier
            U[i, k:] -= L[i, k] * U[k, k:]       # eliminate
    return L, U

A = np.array([[2.0, 1, 1], [4, -6, 0], [-2, 7, 2]])
L, U = lu_nopivot(A)
print("L =\n", L)
print("U =\n", U)
print("L @ U == A:", np.allclose(L @ U, A))
L =
 [[ 1.  0.  0.]
 [ 2.  1.  0.]
 [-1. -1.  1.]]
U =
 [[ 2.  1.  1.]
 [ 0. -8. -2.]
 [ 0.  0.  1.]]
L @ U == A: True

Solving with the factors

Ax=bA\mathbf{x} = \mathbf{b} becomes L(Ux)=bL(U\mathbf{x}) = \mathbf{b}:

  1. Solve Lz=bL\mathbf{z} = \mathbf{b} by forward substitution.
  2. Solve Ux=zU\mathbf{x} = \mathbf{z} by backward substitution (Triangular Systems).

The factorization also gives the determinant almost for free: det⁡A=∏kukk\det A = \prod_k u_{kk} (times ±1\pm 1 for row swaps).

python · try it yourself
import numpy as np
from scipy.linalg import lu_factor, lu_solve, solve_triangular

A = np.array([[2.0, 1, 1], [4, -6, 0], [-2, 7, 2]])
B = np.array([[5.0, 1], [-2, 0], [9, 3]])               # two right-hand sides
lu, piv = lu_factor(A)                                   # factor once
X = lu_solve((lu, piv), B)                               # reuse for both columns
print("X =\n", X)
print("residual:", np.max(np.abs(A @ X - B)))
print("det from U:", np.prod(np.diag(lu)) * (-1) ** np.sum(piv != np.arange(3)), " np.linalg.det:", round(np.linalg.det(A), 10))
X =
 [[ 1.    -0.375]
 [ 1.    -0.25 ]
 [ 2.     2.   ]]
residual: 0.0
det from U: -16.0  np.linalg.det: -16.0

Vectorized elimination

The inner loop over rows is an outer product update of the trailing submatrix, Uk+1:,k:−=ℓ ukTU_{k+1:, k:} \mathrel{-}= \boldsymbol{\ell}\,\mathbf{u}_k^T. Written that way it runs much faster in NumPy, and real libraries go further by working on blocks of columns at once so that most work happens in matrix-matrix products.

python · try it yourself
import numpy as np

def lu_outer(A):
    n = A.shape[0]
    U = A.astype(float).copy()
    L = np.eye(n)
    for k in range(n - 1):
        L[k + 1:, k] = U[k + 1:, k] / U[k, k]
        U[k + 1:, k:] -= np.outer(L[k + 1:, k], U[k, k:])
    return L, U

rng = np.random.default_rng(0)
A = rng.normal(size=(200, 200)) + 20 * np.eye(200)
L, U = lu_outer(A)
print(f"max |LU - A| = {np.max(np.abs(L @ U - A)):.1e}, U upper triangular: {np.allclose(U, np.triu(U))}")
max |LU - A| = 3.2e-14, U upper triangular: True

When it breaks down

Elimination without row exchanges fails if a pivot ukku_{kk} is zero, even for a nonsingular matrix like (0110)\begin{pmatrix} 0 & 1 \\ 1 & 0\end{pmatrix}, and is inaccurate when a pivot is tiny. The cure is partial pivoting (Row Pivoting), which gives PA=LUPA = LU.

In software

  • scipy.linalg.lu(A) returns P,L,UP, L, U; lu_factor/lu_solve keep the compact LAPACK form for repeated solves.
  • np.linalg.solve(A, b) calls LAPACK gesv, which is LU with partial pivoting followed by two triangular solves.
  • Never compute np.linalg.inv(A) @ b: it costs about three times as much as a solve and is less accurate.

Exercises

Exercise 1: Factor by hand

Find the LU factorization of (4363)\begin{pmatrix} 4 & 3 \\ 6 & 3\end{pmatrix}.

Answer

L=(101.51)L = \begin{pmatrix} 1 & 0 \\ 1.5 & 1\end{pmatrix}, U=(430−1.5)U = \begin{pmatrix} 4 & 3 \\ 0 & -1.5\end{pmatrix}.

Solution

Multiplier ℓ21=6/4=1.5\ell_{21} = 6/4 = 1.5; row 2 minus 1.5×1.5 \times row 1 gives (0,3−4.5)=(0,−1.5)(0, 3 - 4.5) = (0, -1.5).

Exercise 2: Many right-hand sides

You must solve Ax=bjA\mathbf{x} = \mathbf{b}_j for 100 vectors bj\mathbf{b}_j, with n=2000n = 2000. Roughly how many flops does factoring once and reusing save compared with 100 separate solves?

Answer

About 99×23n3≈5.3×101199 \times \frac{2}{3}n^3 \approx 5.3 \times 10^{11} flops.

Solution

Each separate solve repeats the 23n3≈5.3×109\frac{2}{3}n^3 \approx 5.3 \times 10^9-flop factorization; the triangular solves (2n22n^2 each) are needed either way.

Exercise 3: A zero pivot (code)

Run lu_nopivot on (0111)\begin{pmatrix} 0 & 1 \\ 1 & 1\end{pmatrix} and then scipy.linalg.lu. What happens?

Answer

The no-pivot version divides by zero (infinite or NaN entries); SciPy swaps the rows and succeeds.

Solution
python · try it yourself
import numpy as np
from scipy.linalg import lu
A = np.array([[0.0, 1], [1, 1]])
with np.errstate(all="ignore"):
    U = A.copy(); m = U[1, 0] / U[0, 0]; U[1] -= m * U[0]
print("no pivoting: multiplier", m, "U row 2", U[1])
P, L, U = lu(A)
print("P =", P.tolist(), "L =", L.tolist(), "U =", U.tolist())
no pivoting: multiplier inf U row 2 [ nan -inf]
P = [[0.0, 1.0], [1.0, 0.0]] L = [[1.0, 0.0], [0.0, 1.0]] U = [[1.0, 1.0], [0.0, 1.0]]

Test yourself

In A=LUA = LU from Gaussian elimination, the entries of LL below the diagonal are…

  1. the pivots
  2. the multipliers
  3. zeros
  4. the entries of AA

After factoring A=LUA = LU once, solving for a new right-hand side costs…

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

Why avoid np.linalg.inv(A) @ b?

  1. It gives a different answer in exact arithmetic
  2. It costs more and is less accurate than solving
  3. It only works for symmetric AA
  4. It is not implemented