Type at least 2 letters. Enter opens the first result, Esc closes.

    Linear Algebra · Lesson 10 · Factorizations, norms and least squares

    The factorization big picture: LU, QR, QΛQ⊤Q\Lambda Q^\top, XΛX−1X\Lambda X^{-1}, UΣV⊤U\Sigma V^\top

    Intermediate 75 min 4 interactive figures 4 videos Colab notebook

    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 A−1A^{-1}; it computes LU or Cholesky and then two triangular solves. Least squares uses QR. PCA uses the SVD or QΛQ⊤Q\Lambda Q^\top. Linear dynamics use XΛX−1X\Lambda X^{-1}. 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 AA as a product of matrices of three easy kinds:

    • triangular: Tx=cTx = c is solved by substitution in about n2n^2 flops;
    • orthogonal: the inverse is the transpose, and lengths are preserved (no error growth);
    • diagonal: nn independent scalar operations.

    Read each factorization as a story about the map x↦Axx \mapsto Ax:

    Factorization Story
    A=LUA = LU elimination: UU is what is left after the row operations, LL records them
    A=QRA = QR an orthonormal basis QQ for the columns; RR holds the coordinates of the columns in it
    S=QΛQ⊤S = Q\Lambda Q^\top rotate to the eigenvector axes, scale each axis, rotate back
    A=XΛX−1A = X\Lambda X^{-1} change to a (possibly skewed) eigenvector basis, scale, change back
    A=UΣV⊤A = U\Sigma V^\top 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 2×22\times 2 matrix.

    Interactive figure: loading…

    Eigenvectors are not singular vectors. The dashed circle is the unit circle and the aqua ellipse is its image under AA; drag the grey dots (the columns of AA) to change it. The blue arrows are the SVD: orthonormal v1,v2v_1, v_2 (faint) go to the ellipse axes σ1u1,σ2u2\sigma_1 u_1, \sigma_2 u_2. The violet lines are the eigenvector directions, where AA 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 σ1σ2=∣det⁡A∣\sigma_1\sigma_2 = |\det A|.

    Quick check

    Which of these 2×22\times 2 matrices has no eigendecomposition A=XΛX−1A = X\Lambda X^{-1}, even with complex numbers?

    3. Definitions and main results #

    LU is elimination, written as matrices #

    Simplest case, 2×22\times 2 with a11≠0a_{11} \neq 0. Subtract ℓ=a21/a11\ell = a_{21}/a_{11} times row 1 from row 2:

    (10−ℓ1)⏟E(a11a12a21a22)=(a11a120a22−ℓa12)=U.\underbrace{\begin{pmatrix}1 & 0\\ -\ell & 1\end{pmatrix}}_{E} \begin{pmatrix}a_{11} & a_{12}\\ a_{21} & a_{22}\end{pmatrix} = \begin{pmatrix}a_{11} & a_{12}\\ 0 & a_{22} - \ell a_{12}\end{pmatrix} = U .

    So A=E−1U=LUA = E^{-1}U = LU with L=(10ℓ1)L = \begin{pmatrix}1 & 0\\ \ell & 1\end{pmatrix}: inverting EE only flips the sign of the multiplier. For n×nn\times n, LL is unit lower triangular (ones on the diagonal) and holds every multiplier ℓij\ell_{ij} below its diagonal; UU is upper triangular with the pivots on its diagonal. Cost: 23n3\tfrac23 n^3 flops for the factorization, then 2n22n^2 per right-hand side (forward substitution Ly=bLy = b, back substitution Ux=yUx = y).

    Interactive figure: loading…

    Step through elimination. Each Next step subtracts a multiple ℓ\ell of the pivot row from a lower row. The multiplier goes into LL at the same position, and a zero appears in UU. The readout max⁡∣PA−LU∣=0\max|PA - LU| = 0 shows that the equation holds after every step, not only at the end. Try zero pivot: without row exchanges elimination stops although AA is invertible; with partial pivoting it finishes, and every ∣ℓij∣≤1|\ell_{ij}| \le 1. The 4×4 case shows how a swap also moves the multipliers already stored in LL.

    Why the multipliers go into LL unchanged #

    Take A=(111233478)A = \begin{pmatrix} 1 & 1 & 1 \\ 2 & 3 & 3 \\ 4 & 7 & 8 \end{pmatrix} (type it into the figure with Edit A to watch the steps). Elimination uses three multipliers:

    1. ℓ21=2/1=2\ell_{21} = 2/1 = 2: row 2 −- 2 · row 1 gives (0,1,1)(0, 1, 1).
    2. ℓ31=4/1=4\ell_{31} = 4/1 = 4: row 3 −- 4 · row 1 gives (0,3,4)(0, 3, 4).
    3. ℓ32=3/1=3\ell_{32} = 3/1 = 3: row 3 −- 3 · (new row 2) gives (0,0,1)(0, 0, 1).

    So U=(111011001)U = \begin{pmatrix} 1 & 1 & 1 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{pmatrix}. Each step is a matrix EijE_{ij}: the identity with −ℓij-\ell_{ij} in position (i,j)(i, j). Then E32E31E21A=UE_{32}E_{31}E_{21}A = U.

    The product of the steps mixes the multipliers.

    E=E32E31E21=(100−2102−31).E = E_{32}E_{31}E_{21} = \begin{pmatrix} 1 & 0 & 0 \\ -2 & 1 & 0 \\ 2 & -3 & 1 \end{pmatrix}.

    The (3,1)(3,1) entry is 22, not −ℓ31=−4-\ell_{31} = -4. It is −ℓ31+ℓ32ℓ21=−4+6-\ell_{31} + \ell_{32}\ell_{21} = -4 + 6: step 3 subtracts a multiple of the new row 2, which already contains −2-2 times row 1.

    The inverse does not mix them.

    L=E−1=E21−1E31−1E32−1=(100210431)=(100ℓ2110ℓ31ℓ321).L = E^{-1} = E_{21}^{-1}E_{31}^{-1}E_{32}^{-1} = \begin{pmatrix} 1 & 0 & 0 \\ 2 & 1 & 0 \\ 4 & 3 & 1 \end{pmatrix} = \begin{pmatrix} 1 & 0 & 0 \\ \ell_{21} & 1 & 0 \\ \ell_{31} & \ell_{32} & 1 \end{pmatrix}.

    Why, in one sentence. When row jj is used as a pivot row, it is already final: it is row jj of UU. So each row of AA is its final row plus the multiples of pivot rows that were subtracted from it:

    row i of A=row i of U+∑j<iℓij (row j of U),\text{row } i \text{ of } A = \text{row } i \text{ of } U + \sum_{j < i} \ell_{ij}\,(\text{row } j \text{ of } U),

    and this is A=LUA = LU, read row by row (lesson 01, row view). Check row 3: (0,0,1)+4 (1,1,1)+3 (0,1,1)=(4,7,8)(0, 0, 1) + 4\,(1, 1, 1) + 3\,(0, 1, 1) = (4, 7, 8) ✓.

    Quick check

    Elimination on a 3×33\times 3 matrix uses the multipliers ℓ21=3\ell_{21} = 3, ℓ31=0\ell_{31} = 0, ℓ32=2\ell_{32} = 2 and no row exchanges. What is LL?

    Theorem (LU without row exchanges). Let AA be invertible, and let AkA_k be its leading k×kk\times k block. A=LUA = LU (unit lower LL, upper UU) exists if and only if det⁡Ak≠0\det A_k \neq 0 for k=1,…,nk = 1, \dots, n. It is then unique, and the pivots are ukk=det⁡Ak/det⁡Ak−1u_{kk} = \det A_k / \det A_{k-1} (with det⁡A0=1\det A_0 = 1).

    Proof of the theorem
    1. (⇒) Write A=LUA = LU in blocks. Because LL is lower and UU upper triangular, the leading blocks satisfy Ak=LkUkA_k = L_k U_k, so det⁡Ak=u11⋯ukk\det A_k = u_{11}\cdots u_{kk} (det⁡Lk=1\det L_k = 1). AA is invertible, so UU is, so every uii≠0u_{ii} \neq 0 and every det⁡Ak≠0\det A_k \neq 0.
    2. (⇐) Run elimination and assume the first k−1k-1 pivots were nonzero. The row operations used so far (row ii minus a multiple of an earlier row) do not change det⁡Ak\det A_k. After them, the leading k×kk\times k block is upper triangular with diagonal u11,…,uk−1,k−1u_{11}, \dots, u_{k-1,k-1} and the current entry in position (k,k)(k,k).
    3. So that entry equals det⁡Ak/det⁡Ak−1≠0\det A_k/\det A_{k-1} \neq 0: the kk-th pivot exists. By induction, elimination never meets a zero pivot, and ukk=det⁡Ak/det⁡Ak−1u_{kk} = \det A_k/\det A_{k-1}.
    4. Uniqueness: if L1U1=L2U2L_1U_1 = L_2U_2, then L2−1L1=U2U1−1L_2^{-1}L_1 = U_2U_1^{-1}. The left side is unit lower triangular, the right side is upper triangular, so both equal II. ■\blacksquare

    In the zero pivot case of the figure, A2=(1224)A_2 = \begin{pmatrix}1 & 2\\ 2 & 4\end{pmatrix} has det⁡A2=0\det A_2 = 0, so the theorem says the second pivot must be 0.

    Partial pivoting. A zero pivot stops elimination even when AA is invertible ((0111)\begin{pmatrix}0&1\\1&1\end{pmatrix}), and a tiny pivot destroys accuracy (section 4). So at step kk, swap in the row with the largest ∣aik∣|a_{ik}|, i≥ki \ge k. Then every multiplier has ∣ℓij∣≤1|\ell_{ij}| \le 1, and for every square AA there is a permutation matrix PP with PA=LUPA = LU (a column that is already zero is skipped). The worst-case growth of the entries is 2n−12^{n-1}, but in practice it is small, and LU with partial pivoting is the standard dense solver (np.linalg.solve calls LAPACK gesv).

    Interactive figure: loading…

    Shrink the pivot. The system (ε111)x=(12)\begin{pmatrix}\varepsilon & 1\\ 1 & 1\end{pmatrix}x = \begin{pmatrix}1\\2\end{pmatrix} has solution x≈(1,1)x \approx (1, 1) for every small ε\varepsilon, and κ(A)≈4\kappa(A) \approx 4: the problem is easy. Move the slider. Without a row exchange the multiplier is 1/ε1/\varepsilon, UU has entries of size 1/ε1/\varepsilon, and the error follows the dashed line u/εu/\varepsilon until no correct digit is left. With partial pivoting the multiplier is ε\varepsilon 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 A−1A^{-1} #

    Once PA=LUPA = LU is known, Ax=bAx = b becomes LUx=PbLUx = Pb, and two triangular solves finish it: first Ly=PbLy = Pb (forward substitution), then Ux=yUx = y (back substitution). Each costs about n2n^2 flops. The expensive work is all in the factorization, and it does not depend on bb.

    For the predict question (n=1000n = 1000, 500 right-hand sides):

    Plan Once Per right-hand side Total for 500
    factor PA=LUPA = LU, then two triangular solves 23n3≈0.67×109\tfrac23 n^3 \approx 0.67\times 10^9 2n2=2×1062n^2 = 2\times 10^6 ≈1.7×109\approx 1.7\times 10^9
    form A−1A^{-1}, then multiply A−1bA^{-1}b ≈2n3=2×109\approx 2n^3 = 2\times 10^9 2n2=2×1062n^2 = 2\times 10^6 ≈3×109\approx 3\times 10^9

    The inverse needs LU plus nn more solves (one for each column of II), so it is never cheaper. It is also less accurate: x=A−1bx = A^{-1}b usually has a larger residual ∥Ax−b∥\|Ax - b\| than the triangular solves (lesson 13). Use scipy.linalg.lu_factor once, then lu_solve for each bb (or pass all bb as the columns of one matrix).

    Cholesky: LU for symmetric positive definite matrices #

    For SPD SS, elimination needs no row exchanges and every pivot is positive (lesson 07). Symmetry gives U=DL⊤U = DL^\top with D=diag⁡(pivots)D = \operatorname{diag}(\text{pivots}), so S=LDL⊤=(LD1/2)(LD1/2)⊤=GG⊤S = LDL^\top = (LD^{1/2})(LD^{1/2})^\top = GG^\top. Cost 13n3\tfrac13 n^3: half of LU, because symmetry means only half of the matrix has to be computed.

    Quick check

    An LU factorization of a 4000×40004000\times 4000 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?

    QR: orthogonalize the columns #

    Any A∈Rm×nA \in \mathbb{R}^{m\times n} with m≥nm \ge n: A=QRA = QR, with QQ (m×nm\times n, orthonormal columns) and RR (n×nn\times n, upper triangular). Gram–Schmidt gives rij=qi⊤ajr_{ij} = q_i^\top a_j. With full column rank and diag⁡(R)>0\operatorname{diag}(R) > 0 it is unique. Key link: A⊤A=R⊤Q⊤QR=R⊤RA^\top A = R^\top Q^\top Q R = R^\top R. So, for full column rank and diag⁡(R)>0\operatorname{diag}(R) > 0, R⊤R^\top is the Cholesky factor LL of A⊤AA^\top A, obtained without forming A⊤AA^\top A (which squares the condition number). Use: least squares (Rx=Q⊤bRx = Q^\top b), orthonormal bases, the QR eigenvalue algorithm, the range finder of lesson 09. Lesson 12 computes it stably (Householder).

    QΛQ⊤Q\Lambda Q^\top: the spectral decomposition #

    Needs S=S⊤S = S^\top (real). QQ is orthogonal (eigenvectors), Λ\Lambda is real diagonal. Λ\Lambda is unique up to order. QQ 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 f(S)=Qf(Λ)Q⊤f(S) = Qf(\Lambda)Q^\top, normal modes, PD tests.

    XΛX−1X\Lambda X^{-1}: the eigendecomposition #

    Needs nn independent eigenvectors (a diagonalizable AA). It fails for defective matrices such as (0100)\begin{pmatrix}0 & 1\\ 0 & 0\end{pmatrix} (lesson 05: Jordan form). XX is not orthogonal in general, Λ\Lambda may be complex for real AA, and each column of XX can be rescaled (for a repeated eigenvalue, any basis of its eigenspace works). Use: powers Ak=XΛkX−1A^k = X\Lambda^kX^{-1}, linear recurrences, linear ODEs eAt=XeΛtX−1e^{At} = Xe^{\Lambda t}X^{-1}, stability of dynamics. Numerical warning: when XX is ill-conditioned (AA is close to defective), formulas with X−1X^{-1} amplify errors.

    UΣV⊤U\Sigma V^\top: the SVD #

    Any m×nm\times n matrix. UU, VV orthogonal, Σ\Sigma diagonal with σ1≥⋯≥0\sigma_1 \ge \dots \ge 0. The σi\sigma_i are unique; for distinct positive σi\sigma_i the pair (ui,vi)(u_i, v_i) 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 SS: QΛQ⊤Q\Lambda Q^\top is an SVD. Symmetric indefinite: flip the sign of uiu_i for each negative λi\lambda_i; then σi=∣λi∣\sigma_i = |\lambda_i|. More generally σi=∣λi∣\sigma_i = |\lambda_i| for normal matrices (A⊤A=AA⊤A^\top A = AA^\top).
    • Always: σmin⁡≤∣λ∣≤σmax⁡\sigma_{\min} \le |\lambda| \le \sigma_{\max} for every eigenvalue, and ∏iσi=∣det⁡A∣=∏i∣λi∣\prod_i \sigma_i = |\det A| = \prod_i |\lambda_i|.
    • A⊤A=R⊤RA^\top A = R^\top R (QR ↔ Cholesky) and A⊤A=VΣ2V⊤A^\top A = V\Sigma^2V^\top (SVD ↔ spectral).

    The map #

    Costs are leading flop counts for n×nn\times n (Golub and Van Loan); the iterative ones are approximate.

    Needs Factors Unique? Cost Main uses
    PA=LUPA = LU square PP permutation, LL unit lower, UU upper yes, for invertible AA and a fixed PP 23n3\tfrac23 n^3 Ax=bAx = b, many bb, det⁡A\det A
    S=LL⊤S = LL^\top SPD LL lower, diagonal >0> 0 yes 13n3\tfrac13 n^3 SPD solves, sampling, log⁡det⁡\log\det, PD test
    A=QRA = QR any m×nm\times n, m≥nm \ge n QQ orthonormal columns, RR upper yes, if full column rank and rii>0r_{ii} > 0 43n3\tfrac43 n^3 least squares, orthonormal bases
    S=QΛQ⊤S = Q\Lambda Q^\top S=S⊤S = S^\top QQ orthogonal, Λ\Lambda real Λ\Lambda up to order; QQ up to signs / within eigenspaces ≈43n3\approx\tfrac43 n^3 (Λ\Lambda), ≈9n3\approx 9n^3 (with QQ) PCA, quadratic forms, f(S)f(S)
    A=XΛX−1A = X\Lambda X^{-1} nn independent eigenvectors XX eigenvectors, Λ\Lambda eigenvalues (maybe complex) Λ\Lambda up to order; XX up to column scaling (distinct λi\lambda_i) ≈10n3\approx 10n^3 (Λ\Lambda), ≈25n3\approx 25 n^3 (Schur form with vectors) AkA^k, eAte^{At}, dynamics
    A=UΣV⊤A = U\Sigma V^\top any m×nm\times n UU, VV orthogonal, Σ≥0\Sigma \ge 0 Σ\Sigma yes; vectors up to paired signs (distinct σi>0\sigma_i > 0) ≈83n3\approx\tfrac83 n^3 (Σ\Sigma), ≈21n3\approx 21n^3 (UU, Σ\Sigma, VV) rank, low rank, A+A^+, κ\kappa
    Interactive figure: loading…

    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 n×nn\times n orthogonal matrix has n2n^2 entries, but Q⊤Q=IQ^\top Q = I is a symmetric matrix equation: n(n+1)/2n(n+1)/2 independent scalar constraints. So it has n2−n(n+1)/2=n(n−1)/2n^2 - n(n+1)/2 = n(n-1)/2 free parameters (rotation angles). A triangular factor has n(n+1)/2n(n+1)/2 entries, a unit triangular one n(n−1)/2n(n-1)/2.

    Factorization Count Total
    LULU n(n−1)2+n(n+1)2\frac{n(n-1)}{2} + \frac{n(n+1)}{2} n2n^2
    QRQR n(n−1)2+n(n+1)2\frac{n(n-1)}{2} + \frac{n(n+1)}{2} n2n^2
    XΛX−1X\Lambda X^{-1} (n2−n)+n(n^2 - n) + n (each column of XX has a free scale) n2n^2
    UΣV⊤U\Sigma V^\top n(n−1)2+n+n(n−1)2\frac{n(n-1)}{2} + n + \frac{n(n-1)}{2} n2n^2
    QΛQ⊤Q\Lambda Q^\top, LL⊤LL^\top n(n−1)2+n\frac{n(n-1)}{2} + n, or n(n+1)2\frac{n(n+1)}{2} n(n+1)2\frac{n(n+1)}{2}

    Every general factorization accounts for exactly n2n^2 numbers. The symmetric ones give n(n+1)/2n(n+1)/2, 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 kk, you do not need a new O(n3)O(n^3) factorization.

    Theorem (Woodbury). Let AA (n×nn\times n) and CC (k×kk\times k) be invertible, UU be n×kn \times k and VV be k×nk\times n. If C−1+VA−1UC^{-1} + VA^{-1}U is invertible, then

    (A+UCV)−1=A−1−A−1U (C−1+VA−1U)−1 VA−1.(A + UCV)^{-1} = A^{-1} - A^{-1}U\,\big(C^{-1} + VA^{-1}U\big)^{-1}\,VA^{-1}.

    Rank 1 (Sherman–Morrison). With k=1k = 1, C=1C = 1, U=uU = u, V=v⊤V = v^\top:

    (A+uv⊤)−1=A−1−A−1u v⊤A−11+v⊤A−1u,if 1+v⊤A−1u≠0.(A + uv^\top)^{-1} = A^{-1} - \frac{A^{-1}u\,v^\top A^{-1}}{1 + v^\top A^{-1} u}, \qquad \text{if } 1 + v^\top A^{-1}u \ne 0 .

    Small check. A=IA = I, u=v=(1,2)u = v = (1, 2). Then 1+u⊤u=61 + u^\top u = 6 and (I+uu⊤)−1=I−uu⊤/6=(5/6−1/3−1/31/3)(I + uu^\top)^{-1} = I - uu^\top/6 = \begin{pmatrix} 5/6 & -1/3 \\ -1/3 & 1/3 \end{pmatrix}. Directly: I+uu⊤=(2225)I + uu^\top = \begin{pmatrix} 2 & 2 \\ 2 & 5 \end{pmatrix} has determinant 66 and inverse 16(5−2−22)\tfrac16\begin{pmatrix} 5 & -2 \\ -2 & 2 \end{pmatrix} ✓.

    Why it is cheap. If you can apply A−1A^{-1} fast (it is diagonal, or you already have its LU or Cholesky factors), the only new inverse is the k×kk\times k matrix C−1+VA−1UC^{-1} + VA^{-1}U (the capacitance matrix). The cost drops from O(n3)O(n^3) to about O(n2k+k3)O(n^2 k + k^3), or O(nk2+k3)O(nk^2 + k^3) for a diagonal AA.

    Proof: multiply and simplify

    Put W=C−1+VA−1UW = C^{-1} + VA^{-1}U and multiply A+UCVA + UCV by the right-hand side:

    1. (A+UCV)(A−1−A−1UW−1VA−1)=I+UCVA−1−UW−1VA−1−UCVA−1UW−1VA−1(A + UCV)(A^{-1} - A^{-1}UW^{-1}VA^{-1}) = I + UCVA^{-1} - UW^{-1}VA^{-1} - UCVA^{-1}UW^{-1}VA^{-1}.
    2. Group the last two terms: −U (I+CVA−1U) W−1VA−1- U\,(I + CVA^{-1}U)\,W^{-1}VA^{-1}.
    3. I+CVA−1U=C(C−1+VA−1U)=CWI + CVA^{-1}U = C(C^{-1} + VA^{-1}U) = CW, so the group is −UCWW−1VA−1=−UCVA−1-UCWW^{-1}VA^{-1} = -UCVA^{-1}.
    4. What is left is I+UCVA−1−UCVA−1=II + UCVA^{-1} - UCVA^{-1} = I. ■\blacksquare

    ML use: ridge regression with few samples. Let XX be n×dn \times d with n≪dn \ll d (for example 100 samples and 10410^4 features). Ridge needs w=(X⊤X+λId)−1X⊤yw = (X^\top X + \lambda I_d)^{-1}X^\top y, a d×dd\times d solve. Woodbury with A=λIdA = \lambda I_d, U=X⊤U = X^\top, C=InC = I_n, V=XV = X turns it into an n×nn \times n solve:

    1. (λId+X⊤X)−1=1λ(Id−X⊤(λIn+XX⊤)−1X)(\lambda I_d + X^\top X)^{-1} = \tfrac1\lambda\big(I_d - X^\top(\lambda I_n + XX^\top)^{-1}X\big).
    2. Multiply by X⊤yX^\top y and factor out X⊤(λIn+XX⊤)−1X^\top(\lambda I_n + XX^\top)^{-1} on the left: w=1λX⊤(λIn+XX⊤)−1[(λIn+XX⊤)−XX⊤]yw = \tfrac1\lambda X^\top(\lambda I_n + XX^\top)^{-1}\big[(\lambda I_n + XX^\top) - XX^\top\big]y.
    3. The bracket is λIn\lambda I_n, so w=X⊤(XX⊤+λIn)−1yw = X^\top(XX^\top + \lambda I_n)^{-1}y.

    The cost goes from O(d3)O(d^3) to O(n2d+n3)O(n^2 d + n^3). The n×nn\times n matrix XX⊤XX^\top 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: (P−1+H⊤R−1H)−1=P−PH⊤(HPH⊤+R)−1HP(P^{-1} + H^\top R^{-1}H)^{-1} = P - PH^\top(HPH^\top + R)^{-1}HP, which is the posterior covariance of lesson 07 (only an m×mm \times m matrix is inverted, mm = number of observations). L-BFGS applies rank-2 updates of this kind to its inverse Hessian estimate.

    Quick check

    Ridge regression with n=100n = 100 samples and d=10 000d = 10\,000 features. Which linear system should you solve?

    Woodbury is the Schur complement read two ways

    Take the block matrix M=(AUV−C−1)M = \begin{pmatrix} A & U \\ V & -C^{-1} \end{pmatrix} and compute the top-left block of M−1M^{-1} in two ways (lesson 07: block elimination).

    1. Eliminate the bottom-right block first. The Schur complement of −C−1-C^{-1} is A−U(−C−1)−1V=A+UCVA - U(-C^{-1})^{-1}V = A + UCV, and the top-left block of M−1M^{-1} is its inverse, (A+UCV)−1(A + UCV)^{-1}.
    2. Eliminate AA first. The Schur complement of AA is −C−1−VA−1U=−W-C^{-1} - VA^{-1}U = -W, and the block-inverse formula gives the top-left block A−1+A−1U(−W)−1VA−1A^{-1} + A^{-1}U(-W)^{-1}VA^{-1}.
    3. 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 X⊤(XX⊤+λI)−1=(X⊤X+λI)−1X⊤X^\top(XX^\top + \lambda I)^{-1} = (X^\top X + \lambda I)^{-1}X^\top, which you can also check directly: multiply both sides by (X⊤X+λI)(X^\top X + \lambda I) on the left and by (XX⊤+λI)(XX^\top + \lambda I) on the right.

    Answers to section 1. (1) Something else: factor PA=LUPA = LU once (23n3\tfrac23 n^3 flops), then each bb costs 2n22n^2 (two triangular solves). Forming A−1A^{-1} costs about 2n32n^3 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. S=(2112)S = \begin{pmatrix}2 & 1\\ 1 & 2\end{pmatrix}.

    • LU: ℓ=1/2\ell = 1/2, so L=(101/21)L = \begin{pmatrix}1 & 0\\ 1/2 & 1\end{pmatrix}, U=(2103/2)U = \begin{pmatrix}2 & 1\\ 0 & 3/2\end{pmatrix}. Pivots 2,3/22, 3/2; det⁡S=3\det S = 3.
    • Cholesky: D=diag⁡(2,3/2)D = \operatorname{diag}(2, 3/2), so G=LD1/2=(201/23/2)G = LD^{1/2} = \begin{pmatrix}\sqrt2 & 0\\ 1/\sqrt2 & \sqrt{3/2}\end{pmatrix}. Check: GG⊤=(2111/2+3/2)=SGG^\top = \begin{pmatrix}2 & 1\\ 1 & 1/2 + 3/2\end{pmatrix} = S. ✓
    • QR (Gram–Schmidt): q1=(2,1)/5q_1 = (2,1)/\sqrt5, r11=5r_{11} = \sqrt5, r12=q1⊤(1,2)=4/5r_{12} = q_1^\top(1,2) = 4/\sqrt5. The rest is (1,2)−45(2,1)=(−35,65)(1,2) - \tfrac45(2,1) = (-\tfrac35, \tfrac65), with length 3/5=r223/\sqrt5 = r_{22}, so q2=(−1,2)/5q_2 = (-1, 2)/\sqrt5. Check: R⊤R=(5445)=S⊤SR^\top R = \begin{pmatrix}5 & 4\\ 4 & 5\end{pmatrix} = S^\top S. ✓
    • Spectral = SVD: λ=3,1\lambda = 3, 1 with q1=(1,1)/2q_1 = (1,1)/\sqrt2, q2=(1,−1)/2q_2 = (1,-1)/\sqrt2. SS is SPD, so σ=3,1\sigma = 3, 1 and U=V=QU = V = Q. Also XΛX−1X\Lambda X^{-1} with X=QX = Q.
    • Sherman–Morrison: S=I+uu⊤S = I + uu^\top with u=(1,1)u = (1, 1), so S−1=I−uu⊤/(1+2)=13(2−1−12)S^{-1} = I - uu^\top/(1 + 2) = \tfrac13\begin{pmatrix}2 & -1\\ -1 & 2\end{pmatrix}. Check: det⁡S=3\det S = 3 and the 2×22\times 2 inverse formula give the same matrix. ✓

    A non-symmetric matrix. A=(2101)A = \begin{pmatrix}2 & 1\\ 0 & 1\end{pmatrix} (the triangular case of the first figure).

    • Eigenvalues 2,12, 1, eigenvectors (1,0)(1,0) and (1,−1)(1,-1): they meet at 45°45°, not 90°90°. X=(110−1)=X−1X = \begin{pmatrix}1 & 1\\ 0 & -1\end{pmatrix} = X^{-1}, and XΛX−1=AX\Lambda X^{-1} = A. ✓
    • Singular values: A⊤A=(4222)A^\top A = \begin{pmatrix}4 & 2\\ 2 & 2\end{pmatrix} has eigenvalues 3±53 \pm \sqrt5, so σ1,2=3±5≈2.288,0.874\sigma_{1,2} = \sqrt{3\pm\sqrt5} \approx 2.288, 0.874, not ∣λ∣=2,1|\lambda| = 2, 1.
    • Checks: σ1σ2=9−5=2=∣det⁡A∣\sigma_1\sigma_2 = \sqrt{9 - 5} = 2 = |\det A|, and 0.874≤1,2≤2.2880.874 \le 1, 2 \le 2.288. ✓

    Why pivot. (10−20111)x=(12)\begin{pmatrix}10^{-20} & 1\\ 1 & 1\end{pmatrix}x = \begin{pmatrix}1\\2\end{pmatrix} has solution x≈(1,1)x \approx (1, 1). Without a row exchange, step by step in double precision:

    1. The multiplier is ℓ=1/10−20=1020\ell = 1/10^{-20} = 10^{20}.
    2. u22=1−1020u_{22} = 1 - 10^{20} rounds to −1020-10^{20}: the entry a22=1a_{22} = 1 is lost.
    3. The right-hand side becomes 2−10202 - 10^{20}, which also rounds to −1020-10^{20}.
    4. Back substitution: x2=(−1020)/(−1020)=1x_2 = (-10^{20})/(-10^{20}) = 1, then x1=(1−x2)/10−20=0x_1 = (1 - x_2)/10^{-20} = 0.

    The true x1x_1 is about 11. With the rows swapped, ℓ=10−20\ell = 10^{-20} and everything is accurate. This is the right end of the second figure.

    Quick check

    You solve (10−20111)x=(12)\begin{pmatrix}10^{-20} & 1\\ 1 & 1\end{pmatrix}x = \begin{pmatrix}1\\2\end{pmatrix} in double precision by LU without row exchanges. What do you get for x1x_1?

    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 K+σ2IK + \sigma^2 I gives both the solve and log⁡det⁡=2∑ilog⁡Lii\log\det = 2\sum_i \log L_{ii}. Its O(n3)O(n^3) cost is the reason for sparse and low-rank approximations; low-rank (Nyström, inducing-point) approximations K≈UCU⊤K \approx UCU^\top are then inverted with the Woodbury formula.
    • Uncertainty and data assimilation: correlated perturbations x=μ+Lzx = \mu + Lz with z∼N(0,I)z \sim \mathcal{N}(0, I) and Σ=LL⊤\Sigma = LL^\top; square-root Kalman filters. The Kalman update inverts only an m×mm\times m matrix (Woodbury), with mm 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 X⊤(XX⊤+λI)−1yX^\top(XX^\top + \lambda I)^{-1}y.
    • 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 XΛX−1X\Lambda X^{-1} models to data. For non-normal AA the transient behavior can differ a lot from what the eigenvalues suggest.
    • Deep learning: torch.linalg has all of these and differentiates through them. The gradients of eigh contain factors 1/(λi−λj)1/(\lambda_i - \lambda_j) (for svd, 1/(σi2−σj2)1/(\sigma_i^2 - \sigma_j^2)), so they become unstable when eigenvalues or singular values are close.

    7. Common mistakes #

    • Computing A−1A^{-1} to solve Ax=bAx = b. About 3× the work of LU, and less accurate.
    • LU without pivoting on a general matrix.
    • Building LL from the product of the elimination steps. E32E31E21E_{32}E_{31}E_{21} mixes the multipliers; LL is its inverse, which holds them unchanged.
    • Calling eig on a symmetric matrix. Use eigh: real eigenvalues, orthonormal eigenvectors, faster.
    • Assuming A=XΛX−1A = X\Lambda X^{-1} exists, or that XX is orthogonal.
    • Assuming σi=∣λi∣\sigma_i = |\lambda_i| for a non-normal matrix.
    • Reading SciPy's LU as PA=LUPA = LU. scipy.linalg.lu returns A=p l uA = p\,l\,u, so P=p⊤P = p^\top.
    • Using Woodbury when it does not help. It pays off only when A−1A^{-1} is cheap to apply and k≪nk \ll n. Repeated rank-1 updates also accumulate rounding error; refactor from time to time.

    8. Check yourself #

    1. Factor A=(2114−60−272)A = \begin{pmatrix}2 & 1 & 1\\ 4 & -6 & 0\\ -2 & 7 & 2\end{pmatrix} as LULU and give det⁡A\det A.
      AnswerL=(100210−1−11)L = \begin{pmatrix}1&0&0\\2&1&0\\-1&-1&1\end{pmatrix}, U=(2110−8−2001)U = \begin{pmatrix}2&1&1\\0&-8&-2\\0&0&1\end{pmatrix}, det⁡A=2⋅(−8)⋅1=−16\det A = 2\cdot(-8)\cdot 1 = -16. (This is the *3×3 example* of the LU figure.)
    2. Which factorization? (a) 1000 solves with the same SPD covariance; (b) an overdetermined least-squares fit with κ(A)=108\kappa(A) = 10^8; (c) A100A^{100} for a diagonalizable AA with a well-conditioned XX; (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 κ(A⊤A)=1016\kappa(A^\top A) = 10^{16}. (c) XΛ100X−1X\Lambda^{100}X^{-1}. (d) Truncated SVD.
    3. A 2×22\times 2 matrix has eigenvalues 22 and 11 and σ1=2.288\sigma_1 = 2.288. What is σ2\sigma_2?
      Answerσ1σ2=∣det⁡A∣=∣λ1λ2∣=2\sigma_1\sigma_2 = |\det A| = |\lambda_1\lambda_2| = 2, so σ2=2/2.288≈0.874\sigma_2 = 2/2.288 \approx 0.874.
    4. In PA=LUPA = LU with partial pivoting, why is ∣ℓij∣≤1|\ell_{ij}| \le 1, and why does it matter?
      AnswerThe pivot is the largest entry in absolute value in its column (rows ≥k\ge k), so each multiplier aik/akka_{ik}/a_{kk} has absolute value at most 1. Small multipliers keep the entries of UU from growing, which keeps rounding errors small (backward stable in practice).
    5. Why does S=QΛQ⊤S = Q\Lambda Q^\top have n(n+1)/2n(n+1)/2 parameters and not n2n^2?
      AnswerQQ has n(n−1)/2n(n-1)/2 (orthogonality removes n(n+1)/2n(n+1)/2 of its n2n^2 entries) and Λ\Lambda has nn: total n(n+1)/2n(n+1)/2, the number of free entries of a symmetric matrix.
    6. You know A−1A^{-1} for a 1000×10001000 \times 1000 matrix. Then one entry changes: a37a_{37} grows by δ\delta. How do you get the new inverse in O(n2)O(n^2)?
      AnswerThe change is the rank-1 matrix δ e3e7⊤\delta\, e_3 e_7^\top. Sherman–Morrison with u=δe3u = \delta e_3, v=e7v = e_7 gives (A+δe3e7⊤)−1=A−1−δ (A−1e3)(e7⊤A−1)/(1+δ e7⊤A−1e3)(A + \delta e_3e_7^\top)^{-1} = A^{-1} - \delta\, (A^{-1}e_3)(e_7^\top A^{-1}) / (1 + \delta\, e_7^\top A^{-1} e_3): column 3 and row 7 of A−1A^{-1}, one outer product, O(n2)O(n^2) work. It fails if 1+δ(A−1)73=01 + \delta (A^{-1})_{73} = 0: then the new matrix is singular.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What do PP, LL and UU store in PA=LUPA = LU?

    2. Why does each multiplier ℓij\ell_{ij} go into LL unchanged?

    3. Why is partial pivoting used?

    4. What are the leading costs of LU and of Cholesky for an n×nn\times n matrix, and of each solve after them?

    5. Why should a solver never form A−1A^{-1}?

    6. Which factorization do you use for a least-squares problem, and why not the normal equations?

    7. When does A=XΛX−1A = X\Lambda X^{-1} exist? Give a matrix where it does not.

    8. Which factorization exists for every m×nm\times n matrix?

    9. State the Woodbury formula.

    10. Count the free parameters of A=QRA = QR for an n×nn\times n matrix.

    Open the review →

    9. Interview angle #

    • "How do you solve Ax=bAx = b for many bb?" — Factor once (LU, or Cholesky if SPD), then O(n2)O(n^2) per right-hand side. Never form A−1A^{-1}.
    • "How do you sample from N(μ,Σ)\mathcal{N}(\mu, \Sigma)?" — x=μ+Lzx = \mu + Lz with Σ=LL⊤\Sigma = LL^\top; if Σ\Sigma is only PSD, use QΛ1/2zQ\Lambda^{1/2}z from eigh.
    • "Eigendecomposition vs SVD?" — The SVD always exists, with two orthonormal bases and σ≥0\sigma \ge 0; the eigendecomposition may not exist, uses one (skewed) basis, and describes AkA^k.
    • "What do LU, Cholesky, QR and the SVD cost?" — 23n3\tfrac23 n^3, 13n3\tfrac13 n^3, 43n3\tfrac43 n^3, and about 21n321n^3 with all singular vectors.
    • "You have 10410^4 features and 100 samples. How do you fit ridge?" — Use the kernel form w=X⊤(XX⊤+λI)−1yw = X^\top(XX^\top + \lambda I)^{-1}y (Woodbury): a 100×100100\times 100 solve instead of a 104×10410^4\times 10^4 one.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. Write LU with partial pivoting, PA=LUPA = LU, and compare it with scipy.linalg.lu.
    2. Write forward and back substitution, and solve many right-hand sides with one factorization.
    3. Write the Cholesky factorization of an SPD matrix.
    4. Use the Cholesky factor to draw correlated samples with a given covariance.
    5. Count the free parameters of LU, QR, QΛQ⊤Q\Lambda Q^\top, XΛX−1X\Lambda X^{-1} and the SVD.

    The notebook also shows the tiny-pivot failure, the worst-case growth 2n−12^{n-1} of partial pivoting, and a demo of the Woodbury formula (ridge with n≪dn \ll d, timed against the d×dd \times d solve).

    11. Watch and read #

    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play