The factorization big picture: LU, QR, , ,
Before this lesson: lesson 05 (eigenvalues, diagonalization and Jordan form), lesson 07 (positive definite matrices, Cholesky and the Schur complement) and lesson 08 (the SVD). Time: about 75 minutes, plus the notebook.
Why this matters #
Almost every numerical method follows one pattern: factor once, then do cheap operations with the factors. A solver never computes ; it computes LU or Cholesky and then two triangular solves. Least squares uses QR. PCA uses the SVD or . Linear dynamics use . Gaussian processes, Kalman filters and quasi-Newton methods (L-BFGS) update inverses with the Woodbury formula. Knowing which factorization fits which problem, and what it costs, is a standard interview question and a daily decision in scientific computing (implicit time stepping, Gaussian processes, data assimilation).
1. Predict first #
2. The picture #
Each factorization writes as a product of matrices of three easy kinds:
- triangular: is solved by substitution in about flops;
- orthogonal: the inverse is the transpose, and lengths are preserved (no error growth);
- diagonal: independent scalar operations.
Read each factorization as a story about the map :
| Factorization | Story |
|---|---|
| elimination: is what is left after the row operations, records them | |
| an orthonormal basis for the columns; holds the coordinates of the columns in it | |
| rotate to the eigenvector axes, scale each axis, rotate back | |
| change to a (possibly skewed) eigenvector basis, scale, change back | |
| rotate, scale, rotate, with two different orthonormal bases |
The last three rows are easy to mix up. The figure puts them side by side for a matrix.
Eigenvectors are not singular vectors. The dashed circle is the unit circle and the aqua ellipse is its image under ; drag the grey dots (the columns of ) to change it. The blue arrows are the SVD: orthonormal (faint) go to the ellipse axes . The violet lines are the eigenvector directions, where only stretches. Try symmetric: the two pictures agree. Try triangular, nearly defective and shear: the eigenvectors close up and then collapse to one line, while the singular vectors stay orthogonal. With rotation there is no real eigenvector at all. In every case .
Which of these matrices has no eigendecomposition , even with complex numbers?
The shear has the double eigenvalue but only one eigenvector direction, . So there is no invertible : it is defective (lesson 05). The rotation has no real eigenvector, but its complex eigenvalues are distinct, so a complex exists. Every one of the four matrices has an SVD.
3. Definitions and main results #
LU is elimination, written as matrices #
Simplest case, with . Subtract times row 1 from row 2:
So with : inverting only flips the sign of the multiplier. For , is unit lower triangular (ones on the diagonal) and holds every multiplier below its diagonal; is upper triangular with the pivots on its diagonal. Cost: flops for the factorization, then per right-hand side (forward substitution , back substitution ).
Step through elimination. Each Next step subtracts a multiple of the pivot row from a lower row. The multiplier goes into at the same position, and a zero appears in . The readout shows that the equation holds after every step, not only at the end. Try zero pivot: without row exchanges elimination stops although is invertible; with partial pivoting it finishes, and every . The 4×4 case shows how a swap also moves the multipliers already stored in .
Why the multipliers go into unchanged #
Take (type it into the figure with Edit A to watch the steps). Elimination uses three multipliers:
- : row 2 2 · row 1 gives .
- : row 3 4 · row 1 gives .
- : row 3 3 · (new row 2) gives .
So . Each step is a matrix : the identity with in position . Then .
The product of the steps mixes the multipliers.
The entry is , not . It is : step 3 subtracts a multiple of the new row 2, which already contains times row 1.
The inverse does not mix them.
Why, in one sentence. When row is used as a pivot row, it is already final: it is row of . So each row of is its final row plus the multiples of pivot rows that were subtracted from it:
and this is , read row by row (lesson 01, row view). Check row 3: ✓.
Elimination on a matrix uses the multipliers , , and no row exchanges. What is ?
holds the multipliers unchanged, in their positions. The first option is the product of the elimination steps : its entry shows the mixing. has no mixing and no minus signs.
Theorem (LU without row exchanges). Let be invertible, and let be its leading block. (unit lower , upper ) exists if and only if for . It is then unique, and the pivots are (with ).
Proof of the theorem
- (⇒) Write in blocks. Because is lower and upper triangular, the leading blocks satisfy , so (). is invertible, so is, so every and every .
- (⇐) Run elimination and assume the first pivots were nonzero. The row operations used so far (row minus a multiple of an earlier row) do not change . After them, the leading block is upper triangular with diagonal and the current entry in position .
- So that entry equals : the -th pivot exists. By induction, elimination never meets a zero pivot, and .
- Uniqueness: if , then . The left side is unit lower triangular, the right side is upper triangular, so both equal .
In the zero pivot case of the figure, has , so the theorem says the second pivot must be 0.
Partial pivoting. A zero pivot stops elimination even when is invertible
(), and a tiny pivot destroys accuracy (section 4).
So at step , swap in the row with the largest , . Then every
multiplier has , and for every square there is a permutation
matrix with (a column that is already zero is skipped). The worst-case growth of
the entries is , but in practice it is small, and LU with partial pivoting is the
standard dense solver (np.linalg.solve calls LAPACK gesv).
Shrink the pivot. The system has solution for every small , and : the problem is easy. Move the slider. Without a row exchange the multiplier is , has entries of size , and the error follows the dashed line until no correct digit is left. With partial pivoting the multiplier is and the answer is correct to the last bit. The failure is in the algorithm, not in the problem.
Factor once, solve many: never form #
Once is known, becomes , and two triangular solves finish it: first (forward substitution), then (back substitution). Each costs about flops. The expensive work is all in the factorization, and it does not depend on .
For the predict question (, 500 right-hand sides):
| Plan | Once | Per right-hand side | Total for 500 |
|---|---|---|---|
| factor , then two triangular solves | |||
| form , then multiply |
The inverse needs LU plus more solves (one for each column of ), so it is never cheaper.
It is also less accurate: usually has a larger residual than the
triangular solves (lesson 13). Use scipy.linalg.lu_factor once, then lu_solve for each
(or pass all as the columns of one matrix).
Cholesky: LU for symmetric positive definite matrices #
For SPD , elimination needs no row exchanges and every pivot is positive (lesson 07). Symmetry gives with , so . Cost : half of LU, because symmetry means only half of the matrix has to be computed.
An LU factorization of a matrix takes 2 seconds on your machine. About how long does a Cholesky factorization of a symmetric positive definite matrix of the same size take?
LU costs about flops and Cholesky about , because symmetry halves the work. The square roots cost almost nothing next to . "Both are " is true but ignores the constant.
QR: orthogonalize the columns #
Any with : , with (, orthonormal columns) and (, upper triangular). Gram–Schmidt gives . With full column rank and it is unique. Key link: . So, for full column rank and , is the Cholesky factor of , obtained without forming (which squares the condition number). Use: least squares (), orthonormal bases, the QR eigenvalue algorithm, the range finder of lesson 09. Lesson 12 computes it stably (Householder).
: the spectral decomposition #
Needs (real). is orthogonal (eigenvectors), is real diagonal. is unique up to order. is unique up to the sign of each column when the eigenvalues are distinct; inside a repeated eigenspace any orthonormal basis works. Use: PCA, quadratic forms, matrix functions , normal modes, PD tests.
: the eigendecomposition #
Needs independent eigenvectors (a diagonalizable ). It fails for defective matrices such as (lesson 05: Jordan form). is not orthogonal in general, may be complex for real , and each column of can be rescaled (for a repeated eigenvalue, any basis of its eigenspace works). Use: powers , linear recurrences, linear ODEs , stability of dynamics. Numerical warning: when is ill-conditioned ( is close to defective), formulas with amplify errors.
: the SVD #
Any matrix. , orthogonal, diagonal with . The are unique; for distinct positive the pair is unique up to a common sign. Use: rank, best low-rank approximation, pseudoinverse, condition number, PCA, matrix norms (lesson 11).
How they relate #
- Symmetric PSD : is an SVD. Symmetric indefinite: flip the sign of for each negative ; then . More generally for normal matrices ().
- Always: for every eigenvalue, and .
- (QR ↔ Cholesky) and (SVD ↔ spectral).
The map #
Costs are leading flop counts for (Golub and Van Loan); the iterative ones are approximate.
| Needs | Factors | Unique? | Cost | Main uses | |
|---|---|---|---|---|---|
| square | permutation, unit lower, upper | yes, for invertible and a fixed | , many , | ||
| SPD | lower, diagonal | yes | SPD solves, sampling, , PD test | ||
| any , | orthonormal columns, upper | yes, if full column rank and | least squares, orthonormal bases | ||
| orthogonal, real | up to order; up to signs / within eigenspaces | (), (with ) | PCA, quadratic forms, | ||
| independent eigenvectors | eigenvectors, eigenvalues (maybe complex) | up to order; up to column scaling (distinct ) | (), (Schur form with vectors) | , , dynamics | |
| any | , orthogonal, | yes; vectors up to paired signs (distinct ) | (), (, , ) | rank, low rank, , |
Answer the two questions on the left; the card on the right gives the factorization. It shows the cost of factoring once, the cost of each later use, the NumPy/SciPy call and the reason. Change one answer at a time and see which property of the matrix changes the choice. Then answer the Check yourself scenarios at the bottom before you read the explanation.
Counting parameters #
An orthogonal matrix has entries, but is a symmetric matrix equation: independent scalar constraints. So it has free parameters (rotation angles). A triangular factor has entries, a unit triangular one .
| Factorization | Count | Total |
|---|---|---|
| (each column of has a free scale) | ||
| , | , or |
Every general factorization accounts for exactly numbers. The symmetric ones give , which is exactly the number of free entries of a symmetric matrix. A count that does not match is a sign of a wrong assumption.
Low-rank updates: the Sherman–Morrison–Woodbury formula #
Often the matrix changes a little after you have factored it: one new data point, one new observation, one quasi-Newton step. If the change has low rank , you do not need a new factorization.
Theorem (Woodbury). Let () and () be invertible, be and be . If is invertible, then
Rank 1 (Sherman–Morrison). With , , , :
Small check. , . Then and . Directly: has determinant and inverse ✓.
Why it is cheap. If you can apply fast (it is diagonal, or you already have its LU or Cholesky factors), the only new inverse is the matrix (the capacitance matrix). The cost drops from to about , or for a diagonal .
Proof: multiply and simplify
Put and multiply by the right-hand side:
- .
- Group the last two terms: .
- , so the group is .
- What is left is .
ML use: ridge regression with few samples. Let be with (for example 100 samples and features). Ridge needs , a solve. Woodbury with , , , turns it into an solve:
- .
- Multiply by and factor out on the left: .
- The bracket is , so .
The cost goes from to . The matrix holds the inner products of the samples: this is the kernel form of ridge regression, the starting point of kernel ridge regression and Gaussian processes. The Kalman filter uses Woodbury in the same way: , which is the posterior covariance of lesson 07 (only an matrix is inverted, = number of observations). L-BFGS applies rank-2 updates of this kind to its inverse Hessian estimate.
Ridge regression with samples and features. Which linear system should you solve?
Woodbury gives . A Cholesky of a matrix is almost free, while the one costs about flops. The pseudoinverse gives the solution (minimum-norm least squares), not ridge.
Woodbury is the Schur complement read two ways
Take the block matrix and compute the top-left block of in two ways (lesson 07: block elimination).
- Eliminate the bottom-right block first. The Schur complement of is , and the top-left block of is its inverse, .
- Eliminate first. The Schur complement of is , and the block-inverse formula gives the top-left block .
- Both are the same block of the same matrix, so they are equal. This is the Woodbury formula.
The same identity gives the push-through identity , which you can also check directly: multiply both sides by on the left and by on the right.
Answers to section 1. (1) Something else: factor once ( flops), then each costs (two triangular solves). Forming costs about and gives less accurate solutions. (2) No: defective matrices have no eigendecomposition. Yes: every matrix, of any shape, has an SVD.
4. Worked example #
One symmetric matrix, all factorizations. .
- LU: , so , . Pivots ; .
- Cholesky: , so . Check: . ✓
- QR (Gram–Schmidt): , , . The rest is , with length , so . Check: . ✓
- Spectral = SVD: with , . is SPD, so and . Also with .
- Sherman–Morrison: with , so . Check: and the inverse formula give the same matrix. ✓
A non-symmetric matrix. (the triangular case of the first figure).
- Eigenvalues , eigenvectors and : they meet at , not . , and . ✓
- Singular values: has eigenvalues , so , not .
- Checks: , and . ✓
Why pivot. has solution . Without a row exchange, step by step in double precision:
- The multiplier is .
- rounds to : the entry is lost.
- The right-hand side becomes , which also rounds to .
- Back substitution: , then .
The true is about . With the rows swapped, and everything is accurate. This is the right end of the second figure.
You solve in double precision by LU without row exchanges. What do you get for ?
The multiplier swamps , so exactly and . The problem is well conditioned; the algorithm without pivoting is unstable. No division by zero happens, because the pivot is not zero.
5. In code #
The libraries confirm the worked example. The notebook for this lesson has these cells and the exercises.
import numpy as np
import scipy.linalg as sl
S = np.array([[2.0, 1.0], [1.0, 2.0]])
p, l, u = sl.lu(S) # SciPy convention: S = p @ l @ u
print(l, u) # l = [[1,0],[0.5,1]], u = [[2,1],[0,1.5]]
G = np.linalg.cholesky(S) # lower triangular, positive diagonal
print(G) # [[1.414 0], [0.707 1.225]]
Q, R = np.linalg.qr(S) # Householder (LAPACK geqrf): signs may differ
print(np.abs(R)) # |R| = [[√5, 4/√5], [0, 3/√5]] = [[2.236 1.789] [0 1.342]]
print(np.allclose(R.T @ R, S.T @ S)) # True: Rᵀ is (up to signs) the Cholesky factor of SᵀS
lam, V = np.linalg.eigh(S) # symmetric: real λ, orthonormal V (LAPACK syevd)
print(lam, np.linalg.svd(S, compute_uv=False)) # [1. 3.] [3. 1.] (SPD: σ = λ)
A = np.array([[2.0, 1.0], [0.0, 1.0]])
lam, X = np.linalg.eig(A) # general (LAPACK geev): X is not orthogonal
print(lam.real, abs(X[:, 0] @ X[:, 1])) # [2. 1.] 0.707... (= cos 45°)
print(np.linalg.svd(A, compute_uv=False)) # [2.288 0.874]: not |λ|
# The multipliers go into L unchanged (no row exchanges here).
A3 = np.array([[1., 1, 1], [2, 3, 3], [4, 7, 8]])
E21 = np.array([[1., 0, 0], [-2, 1, 0], [0, 0, 1]])
E31 = np.array([[1., 0, 0], [0, 1, 0], [-4, 0, 1]])
E32 = np.array([[1., 0, 0], [0, 1, 0], [0, -3, 1]])
E = E32 @ E31 @ E21
print(E @ A3) # U = [[1,1,1],[0,1,1],[0,0,1]]
print(E) # [[1,0,0],[-2,1,0],[2,-3,1]]: the (3,1) entry is mixed
print(np.linalg.inv(E)) # L = [[1,0,0],[2,1,0],[4,3,1]]: the multipliers
# Factor once, solve many right-hand sides.
rng = np.random.default_rng(0)
B = rng.standard_normal((300, 300)) + 300 * np.eye(300)
rhs = rng.standard_normal((300, 500))
lu_piv = sl.lu_factor(B) # PA = LU, 2n³/3 flops, done once
Xs = sl.lu_solve(lu_piv, rhs) # 2n² flops per right-hand side
print(np.allclose(B @ Xs, rhs)) # True
# Sherman–Morrison and ridge with n << d (Woodbury).
uu = np.array([1.0, 2.0])
print(np.allclose(np.linalg.inv(np.eye(2) + np.outer(uu, uu)), np.eye(2) - np.outer(uu, uu) / 6)) # True
Xd, yd, lam_r = rng.standard_normal((5, 40)), rng.standard_normal(5), 0.3
w_primal = np.linalg.solve(Xd.T @ Xd + lam_r * np.eye(40), Xd.T @ yd) # 40 x 40 solve
w_dual = Xd.T @ np.linalg.solve(Xd @ Xd.T + lam_r * np.eye(5), yd) # 5 x 5 solve
print(np.allclose(w_primal, w_dual)) # True
# A tiny pivot without row exchange, done by hand for the 2x2 system.
e = 1e-20
ell = 1 / e # multiplier 1e20
u22 = 1 - ell * 1 # rounds to -1e20: the "1" is lost
x2 = (2 - ell * 1) / u22 # 1.0
x1 = (1 - x2) / e # 0.0, but the true x1 is about 1
print(x1, x2, np.linalg.solve([[e, 1], [1, 1]], [1, 2])) # 0.0 1.0 [1. 1.]
What np.linalg.svd runs
np.linalg.svd calls LAPACK gesdd: Householder bidiagonalization, then a
divide-and-conquer solver for the bidiagonal SVD when singular vectors are wanted.
Reference LAPACK (bdsdc) solves only the small blocks (size at most 25) with QR
iteration, and uses the dqds algorithm when only singular values are wanted. So the main
solver for the bidiagonal matrix is divide and conquer, not QR iteration.
6. Where it shows up #
- Implicit time stepping and Newton solvers (PDE models, climate and weather dynamical cores): a sparse LU of the Jacobian is reused for many steps while the Jacobian is frozen. Sparse factorizations also create fill-in, which decides memory.
- Gaussian processes and kriging: Cholesky of gives both the solve and . Its cost is the reason for sparse and low-rank approximations; low-rank (Nyström, inducing-point) approximations are then inverted with the Woodbury formula.
- Uncertainty and data assimilation: correlated perturbations with and ; square-root Kalman filters. The Kalman update inverts only an matrix (Woodbury), with the number of observations.
- Regression: QR (or SVD when the matrix is rank deficient). With more features than samples, ridge is solved in the kernel form .
- Optimization: BFGS and L-BFGS update an inverse Hessian estimate by rank-2 corrections, which is the Sherman–Morrison–Woodbury idea.
- Dynamics: eigenvalues of a linearization decide stability; DMD and Koopman methods fit models to data. For non-normal the transient behavior can differ a lot from what the eigenvalues suggest.
- Deep learning:
torch.linalghas all of these and differentiates through them. The gradients ofeighcontain factors (forsvd, ), so they become unstable when eigenvalues or singular values are close.
7. Common mistakes #
- Computing to solve . About 3× the work of LU, and less accurate.
- LU without pivoting on a general matrix.
- Building from the product of the elimination steps. mixes the multipliers; is its inverse, which holds them unchanged.
- Calling
eigon a symmetric matrix. Useeigh: real eigenvalues, orthonormal eigenvectors, faster. - Assuming exists, or that is orthogonal.
- Assuming for a non-normal matrix.
- Reading SciPy's LU as .
scipy.linalg.lureturns , so . - Using Woodbury when it does not help. It pays off only when is cheap to apply and . Repeated rank-1 updates also accumulate rounding error; refactor from time to time.
8. Check yourself #
- Factor as and give .
Answer
, , . (This is the *3×3 example* of the LU figure.) - Which factorization? (a) 1000 solves with the same SPD covariance; (b) an overdetermined
least-squares fit with ; (c) for a diagonalizable with a
well-conditioned ; (d) the best rank-5 approximation.
Answer
(a) Cholesky once, then two triangular solves per right-hand side. (b) QR (or SVD); not the normal equations, since . (c) . (d) Truncated SVD. - A matrix has eigenvalues and and . What is ?
Answer
, so . - In with partial pivoting, why is , and why does it matter?
Answer
The pivot is the largest entry in absolute value in its column (rows ), so each multiplier has absolute value at most 1. Small multipliers keep the entries of from growing, which keeps rounding errors small (backward stable in practice). - Why does have parameters and not ?
Answer
has (orthogonality removes of its entries) and has : total , the number of free entries of a symmetric matrix. - You know for a matrix. Then one entry changes: grows by . How do you get the new inverse in ?
Answer
The change is the rank-1 matrix . Sherman–Morrison with , gives : column 3 and row 7 of , one outer product, work. It fails if : then the new matrix is singular.
What do , and store in ?
: the row exchanges. : the upper-triangular result of elimination, with the pivots on its diagonal. : the multipliers , unit lower triangular.
Why does each multiplier go into unchanged?
A pivot row is final when it is used, so row of = row of + (row of ). That is read by rows.
Why is partial pivoting used?
A zero or tiny pivot stops elimination or destroys accuracy. Choosing the largest gives and keeps the entries of small.
What are the leading costs of LU and of Cholesky for an matrix, and of each solve after them?
LU , Cholesky . Then about per right-hand side (two triangular solves).
Why should a solver never form ?
Forming it costs about (LU plus solves), more than LU alone, and is less accurate than two triangular solves.
Which factorization do you use for a least-squares problem, and why not the normal equations?
QR (SVD if the columns are nearly dependent). The normal equations use , whose condition number is .
When does exist? Give a matrix where it does not.
When has independent eigenvectors (diagonalizable). The shear has only one eigenvector direction.
Which factorization exists for every matrix?
The SVD , with orthogonal , and .
State the Woodbury formula.
.
Count the free parameters of for an matrix.
has and has , so in total, as many as has entries.
9. Interview angle #
- "How do you solve for many ?" — Factor once (LU, or Cholesky if SPD), then per right-hand side. Never form .
- "How do you sample from ?" — with ;
if is only PSD, use from
eigh. - "Eigendecomposition vs SVD?" — The SVD always exists, with two orthonormal bases and ; the eigendecomposition may not exist, uses one (skewed) basis, and describes .
- "What do LU, Cholesky, QR and the SVD cost?" — , , , and about with all singular vectors.
- "You have features and 100 samples. How do you fit ridge?" — Use the kernel form (Woodbury): a solve instead of a one.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
- Write LU with partial pivoting, , and compare it with
scipy.linalg.lu. - Write forward and back substitution, and solve many right-hand sides with one factorization.
- Write the Cholesky factorization of an SPD matrix.
- Use the Cholesky factor to draw correlated samples with a given covariance.
- Count the free parameters of LU, QR, , and the SVD.
The notebook also shows the tiny-pivot failure, the worst-case growth of partial pivoting, and a demo of the Woodbury formula (ridge with , timed against the solve).
11. Watch and read #
- Gilbert Strang, MIT 18.06, lecture 4: Factorization into A = LU (course page with notes and exercises).
- Driscoll and Braun, Fundamentals of Numerical Computation, free online: §2.4 LU factorization and §2.6 Row pivoting.
- Golub and Van Loan, Matrix Computations, 4th edition: §3.2 and §3.4 (LU, pivoting), §4.2 (Cholesky), §5.2 (QR), §7.5 and §8.3 (QR algorithm), §8.6 (SVD); §2.1.4 (the Sherman–Morrison–Woodbury formula).
- Nick Higham, "What is the Sherman–Morrison–Woodbury formula?": the formula, a derivation, and where it is used.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.