Course contents 05 / 16

05 / 16 · Linear Algebra

Symmetric matrices and quadratic forms

Why a symmetric matrix is a stretch along perpendicular axes, how its eigenvalues decide the shape of a quadratic function, how to test and factor positive definite matrices, and where a quadratic grows fastest.

On this page 7

Here are two quadratic functions of two variables:

qA(x)=5x12+4x1x2+2x22,qB(x)=x12+4x1x2+x22.\begin{aligned} q_A(x) &= 5x_1^2 + 4x_1x_2 + 2x_2^2, \\ q_B(x) &= x_1^2 + 4x_1x_2 + x_2^2 . \end{aligned}

All their coefficients are positive, and they look alike. Yet qAq_A is positive for every x≠0x \ne 0, a bowl with its minimum at the origin, while qB(1,−1)=1−4+1=−2q_B(1, -1) = 1 - 4 + 1 = -2: qBq_B is a saddle that goes down in some directions. The cross term x1x2x_1x_2 couples the coordinates and hides the shape. Neither the signs of the coefficients nor their sizes say in which directions the function is steep or flat.

The same questions come up whenever a loss is quadratic or nearly so, and near a minimum every smooth loss is. Is a stationary point a minimum? In which direction does the loss rise fastest, and how much faster than in the slowest one? Is a given matrix a valid covariance? Each has one answer: rotate the coordinates until the cross term disappears. The rotation comes from eigenvectors, and the previous note found that general matrices may have complex eigenvalues or too few eigenvectors. The matrices behind quadratic functions are symmetric, and for them nothing goes wrong.

The spectral theorem#

Every quadratic function can be written as x⊤Axx^\top Ax with a symmetric matrix, A=A⊤A = A^\top. For qAq_A the cross coefficient 4 is split equally between the two off-diagonal entries:

A=(5222).A = \begin{pmatrix} 5 & 2 \\ 2 & 2 \end{pmatrix} .

Nothing is lost by insisting on symmetry. A number equals its transpose, so x⊤Mx=x⊤M⊤xx^\top Mx = x^\top M^\top x for any square MM, and averaging the two gives x⊤Mx=x⊤12(M+M⊤) xx^\top Mx = x^\top \tfrac12(M + M^\top)\,x: only the symmetric part of a matrix enters its quadratic form. Covariance matrices, the Gram matrix X⊤XX^\top X of least squares, kernel matrices and the Hessian of every loss with continuous second derivatives (Schwarz’s theorem) are symmetric too.

Spectral theorem. For a symmetric A∈Rn×nA \in \mathbb R^{n \times n} there is an orthogonal matrix QQ (Q⊤Q=IQ^\top Q = I) with columns q1,…,qnq_1, \dots, q_n, and a real diagonal Λ=diag⁡(λ1,…,λn)\Lambda = \operatorname{diag}(\lambda_1, \dots, \lambda_n), such that

  A=QΛQ⊤=λ1q1q1⊤+⋯+λnqnqn⊤.  \boxed{\;A = Q\Lambda Q^\top = \lambda_1q_1q_1^\top + \dots + \lambda_nq_nq_n^\top .\;}

Both halves of the proof use one property: a symmetric matrix moves from one side of an inner product to the other, (Ax)⊤y=x⊤Ay(Ax)^\top y = x^\top Ay.

Real eigenvalues#

Let Ax=λxAx = \lambda x for a vector x∈Cnx \in \mathbb C^n, x≠0x \ne 0, and a number λ\lambda that may a priori be complex; xˉ\bar x is the entrywise complex conjugate. Look at the number xˉ⊤Ax\bar x^\top Ax and take its conjugate:

xˉ⊤Ax‾=x⊤AxˉA is real=(x⊤Axˉ)⊤a number=xˉ⊤A⊤x=xˉ⊤AxA⊤=A.\begin{aligned} \overline{\bar x^\top Ax} &= x^\top A\bar x && A \text{ is real} \\ &= (x^\top A\bar x)^\top && \text{a number} \\ &= \bar x^\top A^\top x \\ &= \bar x^\top Ax && A^\top = A . \end{aligned}

A number equal to its conjugate is real. The same number is λ xˉ⊤x\lambda\, \bar x^\top x, and xˉ⊤x=∣x1∣2+⋯+∣xn∣2\bar x^\top x = \lvert x_1\rvert^2 + \dots + \lvert x_n\rvert^2 is positive, so

λ=xˉ⊤Axxˉ⊤x∈R.\lambda = \frac{\bar x^\top Ax}{\bar x^\top x} \in \mathbb R .

The eigenvector can be chosen real as well: with x=u+ivx = u + iv and AA, λ\lambda real, the real and imaginary parts of Ax=λxAx = \lambda x give Au=λuAu = \lambda u and Av=λvAv = \lambda v, and uu, vv are not both zero.

Orthogonal eigenvectors#

Let Aq1=λ1q1Aq_1 = \lambda_1q_1 and Aq2=λ2q2Aq_2 = \lambda_2q_2 with λ1≠λ2\lambda_1 \ne \lambda_2. Move AA across the inner product:

λ1 q1⊤q2=(Aq1)⊤q2=q1⊤Aq2A⊤=A=λ2 q1⊤q2.\begin{aligned} \lambda_1\, q_1^\top q_2 &= (Aq_1)^\top q_2 \\ &= q_1^\top Aq_2 && A^\top = A \\ &= \lambda_2\, q_1^\top q_2 . \end{aligned}

So (λ1−λ2) q1⊤q2=0(\lambda_1 - \lambda_2)\, q_1^\top q_2 = 0, and since λ1≠λ2\lambda_1 \ne \lambda_2, the eigenvectors are orthogonal.

Proof of the full theorem, including repeated eigenvalues

By induction on nn; for n=1n = 1 there is nothing to prove. The characteristic polynomial has a complex root by the fundamental theorem of algebra (Axler, 2024, 4.12), which is real by the first part, so there is a real unit eigenvector q1q_1 with eigenvalue λ1\lambda_1. Let WW be the subspace of vectors orthogonal to q1q_1, of dimension n−1n - 1. AA maps WW into itself: for w∈Ww \in W, q1⊤Aw=(Aq1)⊤w=λ1q1⊤w=0q_1^\top Aw = (Aq_1)^\top w = \lambda_1q_1^\top w = 0.

Put an orthonormal basis of WW into the columns of U∈Rn×(n−1)U \in \mathbb R^{n \times (n-1)}. The matrix B=U⊤AUB = U^\top AU is symmetric of size n−1n - 1, so by the induction hypothesis B=PΛ′P⊤B = P\Lambda' P^\top with PP orthogonal. The columns of UPUP are orthonormal, lie in WW, and are eigenvectors of AA: AUP=U(U⊤AU)P=UBP=UPΛ′AUP = U(U^\top AU)P = UBP = UP\Lambda', where AU=UU⊤AUAU = UU^\top AU because the columns of AUAU lie in WW and UU⊤UU^\top is the orthogonal projection onto WW. Together with q1q_1 they form an orthonormal eigenbasis of AA. As columns of QQ they give AQ=QΛAQ = Q\Lambda, and multiplying on the right by Q−1=Q⊤Q^{-1} = Q^\top gives A=QΛQ⊤A = Q\Lambda Q^\top.

A repeated eigenvalue therefore never lacks eigenvectors. The characteristic polynomial is det⁡(QΛQ⊤−tI)=det⁡(Λ−tI)=∏i(λi−t)\det(Q\Lambda Q^\top - tI) = \det(\Lambda - tI) = \prod_i(\lambda_i - t), so an eigenvalue of multiplicity mm sits mm times on the diagonal of Λ\Lambda. In eigen-coordinates, (Λ−λI)y=0(\Lambda - \lambda I)y = 0 forces yi=0y_i = 0 wherever λi≠λ\lambda_i \ne \lambda, so the mm matching columns of QQ span its eigenspace, and any orthonormal basis of it will do (Axler, 2024, 7.29, the real spectral theorem).

The two forms of the theorem are one product written two ways. QΛQ\Lambda has the columns λiqi\lambda_iq_i, and a matrix with columns aia_i times a matrix with rows bi⊤b_i^\top is ∑iaibi⊤\sum_i a_ib_i^\top. Each qiqi⊤q_iq_i^\top is the orthogonal projection onto the line through qiq_i. So AA projects xx onto each eigen-axis, scales the projection by λi\lambda_i and adds the results.

Example. For our AA the trace is 7 and the determinant 6, so the characteristic polynomial is λ2−7λ+6=(λ−6)(λ−1)\lambda^2 - 7\lambda + 6 = (\lambda - 6)(\lambda - 1). The null space of A−6IA - 6I is spanned by (2,1)(2, 1), and that of A−IA - I by (1,−2)(1, -2). Their inner product is 2−2=02 - 2 = 0, as the theorem promises, and after normalization q1=(2,1)/5q_1 = (2, 1)/\sqrt5 and q2=(1,−2)/5q_2 = (1, -2)/\sqrt5. The rank-one terms add up to AA:

6⋅15(4221)+1⋅15(1−2−24)=(5222).6 \cdot \frac15\begin{pmatrix} 4 & 2 \\ 2 & 1 \end{pmatrix} + 1 \cdot \frac15\begin{pmatrix} 1 & -2 \\ -2 & 4 \end{pmatrix} = \begin{pmatrix} 5 & 2 \\ 2 & 2 \end{pmatrix} .

Orthonormality makes the eigen-coordinates free. For the non-symmetric matrix of the previous note, the coordinates of xx in the eigenbasis needed a linear solve, c=V−1xc = V^{-1}x. Here Q−1=Q⊤Q^{-1} = Q^\top, so the coordinates are inner products, yi=qi⊤xy_i = q_i^\top x, and lengths are kept: ∥y∥2=x⊤QQ⊤x=∥x∥2\lVert y\rVert^2 = x^\top QQ^\top x = \lVert x\rVert^2, because a square QQ with Q⊤Q=IQ^\top Q = I also has QQ⊤=IQQ^\top = I.

Functions of the matrix act on the eigenvalues alone: Ak=QΛkQ⊤A^k = Q\Lambda^kQ^\top, A−1=QΛ−1Q⊤A^{-1} = Q\Lambda^{-1}Q^\top when no λi\lambda_i is zero, and A1/2=QΛ1/2Q⊤A^{1/2} = Q\Lambda^{1/2}Q^\top when none is negative. Each is checked by multiplying out, with Q⊤Q=IQ^\top Q = I cancelling in the middle: A2=QΛQ⊤QΛQ⊤=QΛ2Q⊤A^2 = Q\Lambda Q^\top Q\Lambda Q^\top = Q\Lambda^2Q^\top. Whitening a Gaussian with Σ−1/2\Sigma^{-1/2}, in the multivariate Gaussian note, is the last of these.

Quadratic forms and their level sets#

The quadratic form of AA is q(x)=x⊤Axq(x) = x^\top Ax. In the eigen-coordinates y=Q⊤xy = Q^\top x it loses its cross terms:

x⊤Ax=x⊤QΛQ⊤x=y⊤Λyy=Q⊤x=λ1y12+⋯+λnyn2.\begin{aligned} x^\top Ax &= x^\top Q\Lambda Q^\top x \\ &= y^\top\Lambda y && y = Q^\top x \\ &= \lambda_1 y_1^2 + \dots + \lambda_n y_n^2 . \end{aligned}

Every question about the shape of qq is now a question about the signs and sizes of the λi\lambda_i.

If all λi>0\lambda_i > 0 and c>0c > 0, the level set q(x)=cq(x) = c is

y12c/λ1+⋯+yn2c/λn=1,\frac{y_1^2}{c/\lambda_1} + \dots + \frac{y_n^2}{c/\lambda_n} = 1 ,

an ellipse in two dimensions and an ellipsoid in more. Its axes point along the eigenvectors qiq_i, with half-length c/λi\sqrt{c/\lambda_i} along qiq_i. A large eigenvalue means a steep direction and a short axis: the function reaches the level cc after a short distance. If some eigenvalues are negative, the level sets are hyperbolas or their higher-dimensional relatives, and the origin is a saddle.

Example. For qAq_A, in the coordinates y1=(2x1+x2)/5y_1 = (2x_1 + x_2)/\sqrt5 and y2=(x1−2x2)/5y_2 = (x_1 - 2x_2)/\sqrt5, the function is 6y12+y226y_1^2 + y_2^2. The level set qA=1q_A = 1 is an ellipse with half-length 1/6=0.4081/\sqrt6 = 0.408 along q1q_1 and 11 along q2q_2; the level set qA=4q_A = 4 is the same ellipse scaled by 2. For qBq_B, with matrix (1221)\begin{pmatrix} 1 & 2 \\ 2 & 1 \end{pmatrix}, the eigenvalues are 3 along (1,1)/2(1, 1)/\sqrt2 and −1-1 along (1,−1)/2(1, -1)/\sqrt2. So qB=3y12−y22q_B = 3y_1^2 - y_2^2: up along one diagonal, down along the other, the saddle of the opening.

Figure

Level sets of a quadratic form and the eigen-axes of its matrix

Level sets of a quadratic form and the eigen-axes of its matrixLeft: two nested ellipses, the level sets q = 1 and q = 4 of the form with matrix [[5, 2], [2, 2]]. Their axes run along the eigenvectors (2, 1) and (1, −2); the half-axes of level 4 are 0.82 along the first and 2 along the second. Right: the form with matrix [[1, 2], [2, 1]] is a saddle. Its level sets q = 1 and q = −1 are hyperbolas with axes along (1, 1) and (1, −1), and the dashed asymptotes are the level q = 0.q = 5x₁² + 4x₁x₂ + 2x₂², λ = 6 and 1q = x₁² + 4x₁x₂ + x₂², λ = 3 and −10.822λ₁ = 6λ₂ = 1q = 1q = 4q = 1q = −1λ₁ = 3λ₂ = −1Level sets of a quadratic form and the eigen-axes of its matrixLeft: two nested ellipses, the level sets q = 1 and q = 4 of the form with matrix [[5, 2], [2, 2]]. Their axes run along the eigenvectors (2, 1) and (1, −2); the half-axes of level 4 are 0.82 along the first and 2 along the second. Right: the form with matrix [[1, 2], [2, 1]] is a saddle. Its level sets q = 1 and q = −1 are hyperbolas with axes along (1, 1) and (1, −1), and the dashed asymptotes are the level q = 0.q = 5x₁² + 4x₁x₂ + 2x₂², λ = 6 and 1q = x₁² + 4x₁x₂ + x₂², λ = 3 and −10.822λ₁ = 6λ₂ = 1q = 1q = 4q = 1q = −1λ₁ = 3λ₂ = −1
Left: q = xᵀAx with A = [[5, 2], [2, 2]]. The levels q = 1 and q = 4 are ellipses along the eigenvectors (2, 1)/√5 (λ = 6, red) and (1, −2)/√5 (λ = 1, blue), with half-axes √(c/λ). Right: the matrix [[1, 2], [2, 1]] gives a saddle; levels q = 1 (amber), q = −1 (green) and q = 0 (dashed).

Every quadratic loss has these level sets around its minimum. The function f(x)=12x⊤Ax−b⊤xf(x) = \tfrac12x^\top Ax - b^\top x with all λi>0\lambda_i > 0 has gradient Ax−bAx - b (the quadratic case), which vanishes at x∗=A−1bx^* = A^{-1}b. Put x=x∗+hx = x^* + h, multiply out the brackets, and use x∗⊤Ah=h⊤Ax∗x^{*\top}Ah = h^\top Ax^*, a number equal to its transpose:

f(x∗+h)=f(x∗)+h⊤(Ax∗−b)+12h⊤Ah=f(x∗)+12h⊤AhAx∗=b.\begin{aligned} f(x^* + h) &= f(x^*) + h^\top(Ax^* - b) + \tfrac12h^\top Ah \\ &= f(x^*) + \tfrac12h^\top Ah && Ax^* = b . \end{aligned}

The level sets are ellipses centred at the minimum, shaped by the eigenvalues of AA. Least squares is this function with A=X⊤XA = X^\top X (the normal equations), and near a minimum every smooth loss looks like it, with AA its Hessian (second-order Taylor).

When the largest eigenvalue is much larger than the smallest, the ellipses are long and thin, and gradient descent zigzags across the narrow valley. The density of a Gaussian has the same level sets with the matrix Σ−1\Sigma^{-1}, whose eigenvalues are 1/λi(Σ)1/\lambda_i(\Sigma). That is why the half-axes of a covariance ellipse are λi\sqrt{\lambda_i}, where those of x⊤Σx=1x^\top \Sigma x = 1 would be 1/λi1/\sqrt{\lambda_i}.

Positive definite and semidefinite matrices#

A symmetric matrix AA is positive definite, A≻0A \succ 0, if x⊤Ax>0x^\top Ax > 0 for every x≠0x \ne 0, and positive semidefinite, A⪰0A \succeq 0, if x⊤Ax≥0x^\top Ax \ge 0 for every xx. A positive definite form is a bowl with ellipsoidal level sets. A semidefinite one may have flat directions, a trough. An indefinite form takes both signs, a saddle.

The definition asks about infinitely many vectors xx. Four finite tests are equivalent to it for a symmetric AA:

A≻0  ⟺  all eigenvalues λi>0  ⟺  all pivots of elimination>0  ⟺  all leading minors>0  ⟺  A=B⊤B, B with independent columns.\begin{aligned} A \succ 0 &\iff \text{all eigenvalues } \lambda_i > 0 \\ &\iff \text{all pivots of elimination} > 0 \\ &\iff \text{all leading minors} > 0 \\ &\iff A = B^\top B,\ B \text{ with independent columns.} \end{aligned}

The eigenvalue test follows from the eigen-coordinates. x⊤Ax=∑iλiyi2x^\top Ax = \sum_i \lambda_iy_i^2 with y=Q⊤xy = Q^\top x, and x↦Q⊤xx \mapsto Q^\top x maps nonzero vectors to nonzero vectors. If every λi>0\lambda_i > 0, the sum is positive as soon as one yiy_i is nonzero. Conversely, x=qix = q_i gives y=eiy = e_i and the value λi\lambda_i, which must then be positive.

The factored form works in both directions. If A=B⊤BA = B^\top B, then x⊤Ax=∥Bx∥2≥0x^\top Ax = \lVert Bx\rVert^2 \ge 0, with equality only when Bx=0Bx = 0, which independent columns allow only for x=0x = 0. If all λi>0\lambda_i > 0, then B=Λ1/2Q⊤B = \Lambda^{1/2}Q^\top does the job.

The kk-th leading minor DkD_k is the determinant of the top-left k×kk \times k block AkA_k. On a positive definite matrix elimination needs no row swap, its kk-th pivot is Dk/Dk−1D_k/D_{k-1} (with D0=1D_0 = 1), and the Cholesky factor carries the square roots of the pivots on its diagonal. The minor test is Sylvester’s criterion.

Proof: pivots, leading minors and definiteness agree

Definite gives positive minors. Pad z∈Rkz \in \mathbb R^k, z≠0z \ne 0, with zeros to x=(z,0)x = (z, 0). Then z⊤Akz=x⊤Ax>0z^\top A_kz = x^\top Ax > 0, so Ak≻0A_k \succ 0, its eigenvalues are positive, and DkD_k, their product, is positive.

Positive minors give A=LL⊤A = LL^\top. By induction on nn: let An−1=L′L′⊤A_{n-1} = L'L'^\top with L′L' lower triangular and a positive diagonal. Split off the last row and column of AA:

(An−1bb⊤c)=(L′0l⊤s)(L′⊤l0s)\begin{aligned} \begin{pmatrix} A_{n-1} & b \\ b^\top & c \end{pmatrix} &= \begin{pmatrix} L' & 0 \\ l^\top & s \end{pmatrix} \begin{pmatrix} L'^\top & l \\ 0 & s \end{pmatrix} \end{aligned}

holds exactly when L′l=bL'l = b, a triangular solve for ll, and s2=c−l⊤ls^2 = c - l^\top l. Taking determinants, Dn=(det⁡L′)2s2=Dn−1s2D_n = (\det L')^2s^2 = D_{n-1}s^2, so s2=Dn/Dn−1>0s^2 = D_n/D_{n-1} > 0 and ss is real and positive. With LL invertible, A=B⊤BA = B^\top B for B=L⊤B = L^\top, and A≻0A \succ 0 by the factored-form test.

Pivots. Elimination without swaps adds multiples of earlier rows to later ones. On the first kk rows and columns these are row operations on AkA_k, which keep DkD_k. After k−1k - 1 steps that block is upper triangular with the pivots d1,…,dkd_1, \dots, d_k on its diagonal, so Dk=d1⋯dkD_k = d_1\cdots d_k and dk=Dk/Dk−1d_k = D_k/D_{k-1}. Positive minors make every pivot positive, and no swap is needed.

Which test for which question#

The tests are equivalent, but each answers a different question cheaply (Strang, 2018, lecture 5).

  • If S≻0S \succ 0 and T≻0T \succ 0, is S+TS + T? The definition answers at once, x⊤(S+T)x=x⊤Sx+x⊤Tx>0x^\top(S + T)x = x^\top Sx + x^\top Tx > 0; the eigenvalues of a sum are not the sums of eigenvalues.
  • Is S−1S^{-1}? The eigenvalues answer: they are 1/λi>01/\lambda_i > 0.
  • Is Q⊤SQQ^\top SQ for an orthogonal QQ? The definition again, with y=Qxy = Qx: x⊤Q⊤SQx=y⊤Sy>0x^\top Q^\top SQx = y^\top Sy > 0.
  • Is a matrix of numbers positive definite? Attempt a Cholesky factorization, the cheapest test.

Two intuitions fail (Merkulov, 2024, lecture 1). Positive entries do not make a matrix positive definite: the matrix of qBq_B has only positive entries and is a saddle. And a positive definite matrix may have negative entries: (2−1−12)\begin{pmatrix} 2 & -1 \\ -1 & 2 \end{pmatrix} has eigenvalues 1 and 3.

The two examples, and the boundary between them#

(5222)\begin{pmatrix} 5 & 2 \\ 2 & 2 \end{pmatrix}(1221)\begin{pmatrix} 1 & 2 \\ 2 & 1 \end{pmatrix}
leading minors55, 6611, −3-3
pivots55, 6/56/511, −3-3
eigenvalues66, 1133, −1-1
verdictpositive definiteindefinite

Every test agrees, and the pivots multiply to the minors: 5⋅6/5=65 \cdot 6/5 = 6.

Semidefinite matrices sit on the boundary. Replace the corner entry 2 of AA by cc. The second leading minor is 5c−45c - 4, so c>0.8c > 0.8 gives a bowl. For c<0.8c < 0.8 the determinant λ1λ2\lambda_1\lambda_2 is negative: a saddle. At c=0.8c = 0.8 the eigenvalues are 5.85.8 and 00: a trough, flat along (2,−5)(2, -5). In floating point the boundary blurs: NumPy’s Cholesky accepts this matrix, because rounding leaves its second pivot at about 10−1610^{-16} instead of 0.

For semidefiniteness the eigenvalue and B⊤BB^\top B tests carry over with ≥\ge, and BB may have dependent columns. The leading minors do not. For (000−1)\begin{pmatrix} 0 & 0 \\ 0 & -1 \end{pmatrix} both leading minors are 0, none is negative, and still q(0,1)=−1q(0, 1) = -1. A semidefinite test by minors needs all principal minors, from every subset of rows and the same columns; in practice one checks the eigenvalues.

Proof: semidefinite exactly when every principal minor is non-negative

Restricting xx to the coordinates of a subset, as for AkA_k above, makes every principal submatrix of A⪰0A \succeq 0 semidefinite, with determinant ≥0\ge 0. Conversely, column jj of A+tIA + tI is aj+teja_j + te_j. The determinant is linear in each column, so it splits into a sum over the sets TT of columns that take tejte_j, and each term is t∣T∣t^{\lvert T\rvert} times the principal minor on the other indices. With all principal minors ≥0\ge 0, the polynomial det⁡(A+tI)=∏i(λi+t)\det(A + tI) = \prod_i(\lambda_i + t) is positive for every t>0t > 0, so no λi\lambda_i equals −t<0-t < 0.

Why covariance and kernel matrices are positive semidefinite#

A covariance matrix, Σ=E[(Z−μ)(Z−μ)⊤]\Sigma = \mathbb E\big[(Z - \mu)(Z - \mu)^\top\big] for a random vector ZZ with mean μ\mu, gives for any fixed vector aa

a⊤Σa=E[a⊤(Z−μ)(Z−μ)⊤a]linearity=E[(a⊤(Z−μ))2]=Var⁡(a⊤Z)≥0.\begin{aligned} a^\top\Sigma a &= \mathbb E\big[a^\top(Z - \mu)(Z - \mu)^\top a\big] && \text{linearity} \\ &= \mathbb E\big[(a^\top(Z - \mu))^2\big] \\ &= \operatorname{Var}(a^\top Z) \ge 0 . \end{aligned}

The quadratic form of a covariance is the variance of a projection. It is zero exactly when some combination a⊤Za^\top Z is constant. For a semidefinite Σ\Sigma, a⊤Σa=∥Σ1/2a∥2a^\top\Sigma a = \lVert\Sigma^{1/2}a\rVert^2 vanishes exactly when Σa=0\Sigma a = 0, so Σ\Sigma is singular exactly when ZZ lies in a hyperplane with probability 1.

The sample covariance S=1nX⊤XS = \frac1n X^\top X of centred data is of the form B⊤BB^\top B. With no more points than dimensions, n≤dn \le d, it is singular. Centring makes the nn rows of XX sum to zero, so XX has rank at most n−1<dn - 1 < d, and X⊤XX^\top X has the null space of XX (X⊤Xv=0X^\top Xv = 0 gives ∥Xv∥2=0\lVert Xv\rVert^2 = 0), hence the same rank; PCA in high dimension works with such matrices (dimensionality reduction).

A kernel k(x,z)=⟨ϕ(x),ϕ(z)⟩k(x, z) = \langle\phi(x), \phi(z)\rangle evaluated on points x1,…,xmx_1, \dots, x_m gives K=ΦΦ⊤K = \Phi\Phi^\top, where Φ\Phi has the rows ϕ(xi)⊤\phi(x_i)^\top. Then c⊤Kc=∥∑iciϕ(xi)∥2≥0c^\top Kc = \lVert\sum_i c_i\phi(x_i)\rVert^2 \ge 0. The kernels note uses the converse: a function whose matrices on every finite set of points are positive semidefinite is a valid kernel. The Hessians of least squares, 2X⊤X2X^\top X, and of logistic regression, X⊤SXX^\top SX with positive weights in the diagonal SS, have the same form; a loss whose Hessian is positive semidefinite everywhere is convex.

Adding a multiple of the identity turns any of these into a definite matrix: A+λIA + \lambda I has the eigenvectors of AA and the eigenvalues λi+λ\lambda_i + \lambda. Ridge regression (X⊤X+λIX^\top X + \lambda I), the noise term of a Gaussian process (K+σn2IK + \sigma_n^2I) and the small jitter added before a Cholesky factorization all do this.

The Cholesky factorization#

To sample from N(μ,Σ)\mathcal N(\mu, \Sigma) or to solve Kα=yK\alpha = y for a kernel matrix, we need a square root of a positive definite matrix that is cheap to compute and to apply. The eigendecomposition gives one, QΛ1/2Q\Lambda^{1/2}, at the price of an iterative algorithm. A triangular one is cheaper. Every A≻0A \succ 0 factors as A=LL⊤A = LL^\top with LL lower triangular and ljj>0l_{jj} > 0, as the proof of the tests above showed.

To find LL, write the entry (i,j)(i, j) of LL⊤LL^\top for i≥ji \ge j. Only k≤jk \le j contribute, since ljk=0l_{jk} = 0 for k>jk > j:

aij=∑k=1nlikljk=∑k<jlikljk+lijljj.\begin{aligned} a_{ij} &= \textstyle\sum_{k=1}^{n} l_{ik}l_{jk} \\ &= \textstyle\sum_{k < j} l_{ik}l_{jk} + l_{ij}l_{jj} . \end{aligned}

For i=ji = j the last term is ljj2l_{jj}^2, and for i>ji > j we divide by ljjl_{jj}:

ljj=ajj−∑k<jljk2,lij=(aij−∑k<jlikljk)/ljj.\begin{aligned} l_{jj} &= \sqrt{a_{jj} - \textstyle\sum_{k < j} l_{jk}^2}, \\ l_{ij} &= \Big(a_{ij} - \textstyle\sum_{k < j} l_{ik}l_{jk}\Big) \big/ l_{jj} . \end{aligned}

Column by column, everything on the right is already known. The first jj rows of LL depend only on AjA_j, and the quantity under the root at step jj is the s2=Dj/Dj−1s^2 = D_j/D_{j-1} of the proof above, the jj-th pivot. If AA is not positive definite, some Dj≤0D_j \le 0; at the first such jj the earlier steps succeed and this quantity is ≤0\le 0, so the algorithm stops. That makes it the cheapest numerical test of definiteness. Column jj computes n−j+1n - j + 1 entries, each with an inner product of length j−1j - 1; the sum is (n−1)n(n+1)/6≈n3/6(n - 1)n(n + 1)/6 \approx n^3/6 multiply–adds, half of the n3/3n^3/3 of LU, with no row swaps (Rakhuba, 2025, lecture 12).

Example. For

K=(422253236)K = \begin{pmatrix} 4 & 2 & 2 \\ 2 & 5 & 3 \\ 2 & 3 & 6 \end{pmatrix}

the three columns of LL come out as follows:

columncomputationentries
1l11=4l_{11} = \sqrt4, l21=2/2l_{21} = 2/2, l31=2/2l_{31} = 2/22,1,12, 1, 1
2l22=5−12l_{22} = \sqrt{5 - 1^2}, l32=(3−1⋅1)/2l_{32} = (3 - 1 \cdot 1)/22,12, 1
3l33=6−12−12l_{33} = \sqrt{6 - 1^2 - 1^2}22

So

L=(200120112),L = \begin{pmatrix} 2 & 0 & 0 \\ 1 & 2 & 0 \\ 1 & 1 & 2 \end{pmatrix},

and the determinant comes with it:

det⁡K=(det⁡L)2=82=64,log⁡det⁡K=2∑jlog⁡ljj=6log⁡2=4.159.\begin{aligned} \det K &= (\det L)^2 = 8^2 = 64, \\ \log\det K &= 2\textstyle\sum_j \log l_{jj} = 6\log 2 = 4.159 . \end{aligned}

Sampling from a Gaussian goes through this factor: if z∼N(0,I)z \sim \mathcal N(0, I), then μ+Lz∼N(μ,LL⊤)\mu + Lz \sim \mathcal N(\mu, LL^\top), the recipe of the multivariate Gaussian note. So does solving with a kernel matrix: Kα=yK\alpha = y becomes two triangular systems, Lu=yLu = y and L⊤α=uL^\top\alpha = u, each in about n2/2n^2/2 multiply–adds, with log⁡det⁡K\log\det K for free; this is how Gaussian process regression computes its posterior and marginal likelihood without forming K−1K^{-1}.

The factorization also exposes a numerical problem. A kernel matrix that is positive definite in exact arithmetic can be numerically singular. Take the RBF kernel exp⁡(−(x−z)2/(2⋅0.52))\exp\big(-(x - z)^2/(2 \cdot 0.5^2)\big) on 50 equally spaced points of [0,1][0, 1]. Cholesky with 150 significant digits succeeds, so the matrix is positive definite, but its last pivot is 1.6⋅10−741.6 \cdot 10^{-74}, and λmin⁡\lambda_{\min} is smaller still. That pivot is lnn2=1/(K−1)nnl_{nn}^2 = 1/(K^{-1})_{nn}, because K−1=L−⊤L−1K^{-1} = L^{-\top}L^{-1} and the last column of the triangular L−1L^{-1} is en/lnne_n/l_{nn}; by the Rayleigh bound below, (K−1)nn≤1/λmin⁡(K^{-1})_{nn} \le 1/\lambda_{\min}.

Rounding the entries to double precision changes KK by some EE with ∥E∥2≤∥E∥F≤u∥K∥F=4.4⋅10−15\lVert E\rVert_2 \le \lVert E\rVert_F \le u\lVert K\rVert_F = 4.4 \cdot 10^{-15}, where u=2−53u = 2^{-53}, and by Weyl’s inequality below that can move every eigenvalue by as much. The computed smallest eigenvalue is −9⋅10−15-9 \cdot 10^{-15}, the largest 38.3, and double-precision Cholesky fails. The jitter 10−10I10^{-10}I makes it succeed, at the price of a slightly different matrix.

The Rayleigh quotient: the extreme directions#

How large can x⊤Axx^\top Ax be for a vector of length 1? This is the steepest direction of a quadratic, the direction of largest variance in PCA, and the largest stretch of a matrix. The Rayleigh quotient R(x)=x⊤Ax/x⊤xR(x) = x^\top Ax/x^\top x, for x≠0x \ne 0, asks the same question without fixing the length.

In eigen-coordinates, with x⊤x=y⊤Q⊤Qy=y⊤yx^\top x = y^\top Q^\top Qy = y^\top y, the quotient is an average of the eigenvalues:

R(x)=λ1y12+⋯+λnyn2y12+⋯+yn2=w1λ1+⋯+wnλn,\begin{aligned} R(x) &= \frac{\lambda_1y_1^2 + \dots + \lambda_ny_n^2}{y_1^2 + \dots + y_n^2} \\ &= w_1\lambda_1 + \dots + w_n\lambda_n , \end{aligned}

with weights wi=yi2/∥y∥2w_i = y_i^2/\lVert y\rVert^2 that are non-negative and sum to 1. An average lies between its smallest and its largest term:

λmin⁡≤R(x)≤λmax⁡.\lambda_{\min} \le R(x) \le \lambda_{\max} .

All the weight sits on λmax⁡\lambda_{\max} when xx is its eigenvector, so the bound is reached there, and likewise for λmin⁡\lambda_{\min}.

Example. For A=(5222)A = \begin{pmatrix} 5 & 2 \\ 2 & 2 \end{pmatrix} and x=(1,1)x = (1, 1), R=(5+4+2)/2=5.5R = (5 + 4 + 2)/2 = 5.5. In eigen-coordinates y=(3,−1)/5y = (3, -1)/\sqrt5, so the weights are 0.90.9 and 0.10.1, and 0.9⋅6+0.1⋅1=5.50.9 \cdot 6 + 0.1 \cdot 1 = 5.5. On the unit circle x=(cos⁡θ,sin⁡θ)x = (\cos\theta, \sin\theta) the quotient is

R(θ)=5cos⁡2θ+4cos⁡θsin⁡θ+2sin⁡2θ=3.5+1.5cos⁡2θ+2sin⁡2θ,\begin{aligned} R(\theta) &= 5\cos^2\theta + 4\cos\theta\sin\theta + 2\sin^2\theta \\ &= 3.5 + 1.5\cos 2\theta + 2\sin 2\theta , \end{aligned}

by the double-angle formulas. Its amplitude is 1.52+22=2.5\sqrt{1.5^2 + 2^2} = 2.5, so it oscillates between 3.5−2.5=13.5 - 2.5 = 1 and 66 with period π\pi, and peaks where tan⁡2θ=2/1.5\tan 2\theta = 2/1.5, at θ=26.57°\theta = 26.57°, the direction of q1=(2,1)/5q_1 = (2, 1)/\sqrt5:

Figure

The Rayleigh quotient on the unit circle

The Rayleigh quotient on the unit circleThe curve R(θ) for θ from 0 to 180 degrees oscillates between 1 and 6. The maximum 6 is at θ = 26.57°, the direction of the eigenvector q₁ = (2, 1)/√5; the minimum 1 is at θ = 116.57°, the direction of q₂. The point θ = 45° gives 5.5. The average value is 3.5.0°45°90°135°180°013.56angle θ of xR(θ) = xᵀAxλ₁ = 6λ₂ = 1tr A / 2 = 3.55.5θ = 26.57°, along q₁θ = 116.57°, along q₂The Rayleigh quotient on the unit circleThe curve R(θ) for θ from 0 to 180 degrees oscillates between 1 and 6. The maximum 6 is at θ = 26.57°, the direction of the eigenvector q₁ = (2, 1)/√5; the minimum 1 is at θ = 116.57°, the direction of q₂. The point θ = 45° gives 5.5. The average value is 3.5.0°45°90°135°180°013.56angle θ of xR(θ) = xᵀAxλ₁ = 6λ₂ = 1tr A / 2 = 3.55.526.57°116.57°
R(θ) = xᵀAx for the unit vector x = (cos θ, sin θ) and A = [[5, 2], [2, 2]]. It stays within [λ₂, λ₁] = [1, 6], with the maximum at q₁ = (2, 1)/√5 (26.57°) and the minimum at q₂ = (1, −2)/√5 (116.57°). The period is 180°, because x and −x give the same value.

The first principal component maximizes the variance w⊤Sww^\top Sw over unit vectors ww, a Rayleigh quotient of the covariance, so it is the top eigenvector (PCA as variance maximization). For any matrix BB, ∥Bx∥2/∥x∥2=x⊤B⊤Bx/x⊤x\lVert Bx\rVert^2/\lVert x\rVert^2 = x^\top B^\top Bx/x^\top x, so the largest factor by which BB stretches a vector is λmax⁡(B⊤B)\sqrt{\lambda_{\max}(B^\top B)}, the spectral norm; the next note builds the SVD on this observation.

Along a unit direction uu, the second derivative of a function with Hessian HH is u⊤Huu^\top Hu, which lies between the extreme eigenvalues of HH. Gradient descent with step η\eta is stable only if η<2/λmax⁡(H)\eta < 2/\lambda_{\max}(H), and the ratio λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min}, the condition number, sets its speed (gradient descent).

Computing the largest eigenvalue: power iteration#

For a large matrix the top eigenpair is found without any factorization: repeat x←Ax/∥Ax∥x \leftarrow Ax/\lVert Ax\rVert and read off R(x)R(x), one matrix–vector product per step. The iterative methods note derives how fast this converges and why the Rayleigh quotient converges twice as fast as the direction.

Intermediate eigenvalues#

Optional depth: the min–max characterization of every eigenvalue. The rest of the note does not depend on it.

With eigenvalues sorted λ1≥⋯≥λn\lambda_1 \ge \dots \ge \lambda_n, the Courant–Fischer theorem says that the kk-th one is the best worst-case Rayleigh quotient over kk-dimensional subspaces:

λk=max⁡dim⁡S=k min⁡x∈S, x≠0R(x).\lambda_k = \max_{\dim S = k}\ \min_{x \in S,\ x \ne 0} R(x) .

The span of q1,…,qkq_1, \dots, q_k attains the maximum: on it, RR is an average of λ1,…,λk\lambda_1, \dots, \lambda_k, so its minimum is λk\lambda_k. No other kk-dimensional subspace does better. It must contain a unit vector orthogonal to q1,…,qk−1q_1, \dots, q_{k-1}, because a subspace SS of dimension kk and the span TT of qk,…,qnq_k, \dots, q_n, of dimension n−k+1n - k + 1, intersect: dim⁡(S∩T)=dim⁡S+dim⁡T−dim⁡(S+T)≥1\dim(S \cap T) = \dim S + \dim T - \dim(S + T) \ge 1 (Axler, 2024, 2.43). On such a vector RR is an average of λk,…,λn\lambda_k, \dots, \lambda_n, at most λk\lambda_k.

Two related facts are used in machine learning. The first is PCA with kk components. For W∈Rn×kW \in \mathbb R^{n \times k} with orthonormal columns, the variance kept is

tr⁡(W⊤AW)=∑iλi∥W⊤qi∥2A=∑iλiqiqi⊤≤λ1+⋯+λk.\begin{aligned} \operatorname{tr}(W^\top AW) &= \textstyle\sum_i \lambda_i\lVert W^\top q_i\rVert^2 && A = \textstyle\sum_i\lambda_iq_iq_i^\top \\ &\le \lambda_1 + \dots + \lambda_k . \end{aligned}

The weights qi⊤WW⊤qiq_i^\top WW^\top q_i lie in [0,1][0, 1], because WW⊤WW^\top is the orthogonal projection onto the columns of WW, and sum to tr⁡(Q⊤WW⊤Q)=tr⁡(W⊤W)=k\operatorname{tr}(Q^\top WW^\top Q) = \operatorname{tr}(W^\top W) = k. Such a sum is largest with weight 1 on the kk largest λi\lambda_i, and W=(q1,…,qk)W = (q_1, \dots, q_k) attains it.

The second is Weyl’s inequality: for symmetric AA and EE, ∣λk(A+E)−λk(A)∣≤∥E∥2\lvert\lambda_k(A + E) - \lambda_k(A)\rvert \le \lVert E\rVert_2. Since E⊤E=E2E^\top E = E^2 has the eigenvalues λi(E)2\lambda_i(E)^2, ∥E∥2=max⁡i∣λi(E)∣\lVert E\rVert_2 = \max_i\lvert\lambda_i(E)\rvert and ∣RE(x)∣≤∥E∥2\lvert R_E(x)\rvert \le \lVert E\rVert_2. Hence RA+E(x)=RA(x)+RE(x)≥RA(x)−∥E∥2R_{A+E}(x) = R_A(x) + R_E(x) \ge R_A(x) - \lVert E\rVert_2 for every xx. The max–min over kk-dimensional subspaces keeps the inequality, so λk(A+E)≥λk(A)−∥E∥2\lambda_k(A + E) \ge \lambda_k(A) - \lVert E\rVert_2, and exchanging AA with A+EA + E gives the other side (Horn and Johnson, 2013, sections 4.2 and 4.3). A sample covariance SS tends to Σ\Sigma entrywise by the law of large numbers, and ∥S−Σ∥2≤∥S−Σ∥F\lVert S - \Sigma\rVert_2 \le \lVert S - \Sigma\rVert_F, so its spectrum is a stable estimate when the sample is large.

Where it breaks: nearly equal eigenvalues#

Weyl’s inequality protects the eigenvalues. Nothing protects the eigenvectors when two eigenvalues are close. Take ε=10−6\varepsilon = 10^{-6} and

A=(1001+ε),A = \begin{pmatrix} 1 & 0 \\ 0 & 1 + \varepsilon \end{pmatrix},

whose eigenvectors are e1e_1 and e2e_2, and add δ=10−6\delta = 10^{-6} to both off-diagonal entries. The eigenvalues move by 6.2⋅10−76.2 \cdot 10^{-7} each, within δ\delta as Weyl promises. The eigenvector of the larger one turns by 12arctan⁡(2δ/ε)=31.7°\tfrac12\arctan(2\delta/\varepsilon) = 31.7°. With δ\delta ten times larger it would turn by 12arctan⁡20=43.6°\tfrac12\arctan 20 = 43.6°, almost 45°45°.

The angle comes from a rotation. For a symmetric matrix with entries a,b,b,ca, b, b, c, the rotation RR by θ\theta has the eigenvectors as columns when the off-diagonal entry of R⊤ARR^\top AR vanishes:

0=(c−a)sin⁡θcos⁡θ+b(cos⁡2θ−sin⁡2θ)=12(c−a)sin⁡2θ+bcos⁡2θ,\begin{aligned} 0 &= (c - a)\sin\theta\cos\theta + b(\cos^2\theta - \sin^2\theta) \\ &= \tfrac12(c - a)\sin 2\theta + b\cos 2\theta , \end{aligned}

so tan⁡2θ=2b/(a−c)\tan 2\theta = 2b/(a - c). Here b=δb = \delta and ∣a−c∣=ε\lvert a - c\rvert = \varepsilon, which gives the angle above.

The angle is set by the ratio of the perturbation to the gap between the eigenvalues, here δ/ε=1\delta/\varepsilon = 1. Only the eigenspace of a cluster of close eigenvalues is well determined; for A=IA = I every orthonormal basis is an eigenbasis. Principal components with nearly equal variances can therefore swap or rotate between two samples of the same data, and an algorithm that tracks individual components across runs must compare subspaces instead.

Symmetry itself can be inexact. X⊤XX^\top X computed in floating point, or a Hessian estimated by finite differences, may be symmetric only up to rounding, and a general eigenvalue routine can then return tiny imaginary parts. Symmetrize, 12(A+A⊤)\tfrac12(A + A^\top), and call a symmetric solver such as numpy.linalg.eigh. The full decomposition costs O(n3)O(n^3), out of reach for a kernel matrix on 10510^5 points; there one computes a few extreme eigenpairs iteratively, or approximates the matrix, as in the cost section of the kernels note.

What you should remember#

  • A symmetric matrix has real eigenvalues and an orthonormal eigenbasis: A=QΛQ⊤=∑iλiqiqi⊤A = Q\Lambda Q^\top = \sum_i\lambda_iq_iq_i^\top.
  • In y=Q⊤xy = Q^\top x, x⊤Ax=∑iλiyi2x^\top Ax = \sum_i\lambda_iy_i^2; for A≻0A \succ 0 the level set q=cq = c has half-axes c/λi\sqrt{c/\lambda_i} along qiq_i.
  • A≻0A \succ 0 iff all eigenvalues, pivots or leading minors are positive, iff A=B⊤BA = B^\top B with independent columns; for A⪰0A \succeq 0 leading minors are not enough.
  • Covariance, Gram and kernel matrices are B⊤BB^\top B, hence semidefinite; +λI+\lambda I makes them definite.
  • Cholesky A=LL⊤A = LL^\top costs n3/6n^3/6 multiply–adds, samples Gaussians as μ+Lz\mu + Lz, and gives log⁡det⁡A=2∑jlog⁡ljj\log\det A = 2\sum_j\log l_{jj}.
  • λmin⁡≤x⊤Ax/x⊤x≤λmax⁡\lambda_{\min} \le x^\top Ax/x^\top x \le \lambda_{\max}; eigenvectors of close eigenvalues are unstable.

Code#

The spectral theorem, the quadratic-form identity, the definiteness tests and the semidefinite boundary, Cholesky by the formula of the note against NumPy, jitter, the Rayleigh quotient on the circle, and the turning eigenvector. It runs in well under a second; digits in the last places can differ across platforms and library versions.

import numpy as np
from scipy.linalg import solve_triangular

# 1. the spectral theorem: real eigenvalues, orthonormal eigenvectors, A = Q Lambda Q^T = sum of rank-one terms
A = np.array([[5.0, 2.0], [2.0, 2.0]])
lam, Q = np.linalg.eigh(A)                      # eigh: for symmetric matrices, eigenvalues in ascending order
print(lam, np.allclose(Q.T @ Q, np.eye(2)), np.allclose(sum(l * np.outer(q, q) for l, q in zip(lam, Q.T)), A))
rng = np.random.default_rng(0)
M = rng.normal(size=(6, 6)); S = M + M.T        # a random symmetric matrix
ls, Qs = np.linalg.eigh(S)
print(np.abs(np.linalg.eigvals(S).imag).max() < 1e-12, np.allclose(Qs.T @ Qs, np.eye(6)), np.allclose(Qs @ np.diag(ls) @ Qs.T, S))
# [1. 6.] True True
# True True True

# 2. the quadratic form in eigen-coordinates: x^T A x = sum lambda_i y_i^2 with y = Q^T x
x = rng.normal(size=2); y = Q.T @ x
q1 = np.array([2.0, 1.0]) / np.sqrt(5)
print(np.isclose(x @ A @ x, (lam * y**2).sum()), round(float((q1 / np.sqrt(6)) @ A @ (q1 / np.sqrt(6))), 6))
# True 1.0: the end of the short half-axis 1/sqrt(6) along q1 lies on the level set q = 1

# 3. definiteness tests: eigenvalues, leading minors, Cholesky; the boundary c = 0.8; the semidefinite trap
def leading_minors(M): return [round(float(np.linalg.det(M[:k, :k])), 6) for k in range(1, len(M) + 1)]
def is_pd_by_cholesky(M):
    try: np.linalg.cholesky(M); return True
    except np.linalg.LinAlgError: return False
for name, M in [('A', A), ('B', np.array([[1.0, 2.0], [2.0, 1.0]])), ('c=0.8', np.array([[5.0, 2.0], [2.0, 0.8]])),
                ('neg', np.array([[2.0, -1.0], [-1.0, 2.0]])), ('trap', np.array([[0.0, 0.0], [0.0, -1.0]]))]:
    print(name, np.linalg.eigvalsh(M).round(6) + 0.0, leading_minors(M), is_pd_by_cholesky(M))
# A [1. 6.] [5.0, 6.0] True
# B [-1.  3.] [1.0, -3.0] False
# c=0.8 [0.  5.8] [5.0, 0.0] True    (rounding leaves the second pivot at about 1e-16)
# neg [1. 3.] [2.0, 3.0] True
# trap [-1.  0.] [0.0, 0.0] False

# 4. covariance and kernel matrices are positive semidefinite; X^T X is singular when n <= d
X = rng.normal(size=(5, 8)); Xc = X - X.mean(axis=0)
ev = np.linalg.eigvalsh(Xc.T @ Xc / 5)
print(ev.min() > -1e-12, int((ev > 1e-10).sum()))   # 5 centred points in 8 dimensions: rank at most 4
pts = rng.normal(size=(30, 2))
K_rbf = np.exp(-((pts[:, None] - pts[None]) ** 2).sum(-1) / 2)
K_dist = np.sqrt(((pts[:, None] - pts[None]) ** 2).sum(-1))       # a distance is not a kernel
print(np.linalg.eigvalsh(K_rbf).min() > -1e-12, round(float(np.linalg.eigvalsh(K_dist).min()), 2))
# True 4
# True -19.26

# 5. Cholesky by the formula of the note, column by column, against NumPy; sampling and two triangular solves
def cholesky(A):
    n = len(A); L = np.zeros_like(A)
    for j in range(n):
        d = A[j, j] - L[j, :j] @ L[j, :j]
        if d <= 0: raise ValueError(f'not positive definite: pivot {j + 1} is {d:.3g}')
        L[j, j] = np.sqrt(d)
        for i in range(j + 1, n):
            L[i, j] = (A[i, j] - L[i, :j] @ L[j, :j]) / L[j, j]
    return L
K = np.array([[4.0, 2.0, 2.0], [2.0, 5.0, 3.0], [2.0, 3.0, 6.0]])
L = cholesky(K)
print(L.tolist(), np.allclose(L, np.linalg.cholesky(K)), round(2 * np.log(np.diag(L)).sum(), 4), round(float(np.log(np.linalg.det(K))), 4))
Z = rng.normal(size=(200_000, 3)) @ L.T
alpha = solve_triangular(L.T, solve_triangular(L, np.array([1.0, 2.0, 3.0]), lower=True), lower=False)
print(np.cov(Z.T).round(1).tolist(), np.allclose(K @ alpha, [1.0, 2.0, 3.0]))
# [[2.0, 0.0, 0.0], [1.0, 2.0, 0.0], [1.0, 1.0, 2.0]] True 4.1589 4.1589
# [[4.0, 2.0, 2.0], [2.0, 5.0, 3.0], [2.0, 3.0, 6.0]] True

# 6. jitter: an RBF kernel matrix that is numerically singular
t = np.linspace(0, 1, 50)
Kt = np.exp(-(t[:, None] - t[None]) ** 2 / (2 * 0.5**2))
e = np.linalg.eigvalsh(Kt)
print(f'{e.max():.1f} {e.min():.1g}', is_pd_by_cholesky(Kt), is_pd_by_cholesky(Kt + 1e-10 * np.eye(50)))
print(f'{2.0**-53 * np.linalg.norm(Kt):.1e}')       # u ||K||_F: the size of the rounding of the entries
from decimal import Decimal, getcontext
getcontext().prec = 150                             # the same Cholesky with 150 significant digits
td = [Decimal(i) / 49 for i in range(50)]
Kd = [[(-2 * (a - b) ** 2).exp() for b in td] for a in td]   # 2 = 1 / (2 * 0.5^2)
Ld = [[Decimal(0)] * 50 for _ in range(50)]
for j in range(50):
    d = Kd[j][j] - sum(Ld[j][k] ** 2 for k in range(j))
    Ld[j][j] = d.sqrt()                             # raises InvalidOperation if d < 0
    for i in range(j + 1, 50):
        Ld[i][j] = (Kd[i][j] - sum(Ld[i][k] * Ld[j][k] for k in range(j))) / Ld[j][j]
print(f'{float(d):.1e}')                            # the last pivot: positive, but tiny
# 38.3 -9e-15 False True
# 4.4e-15
# 1.6e-74

# 7. the Rayleigh quotient on the unit circle
theta = np.linspace(0, np.pi, 100_001)
U = np.stack([np.cos(theta), np.sin(theta)])
Rq = np.einsum('in,ij,jn->n', U, A, U)
print(round(Rq.max(), 6), round(np.degrees(theta[Rq.argmax()]), 1), round(Rq.min(), 6), round(np.degrees(theta[Rq.argmin()]), 1),
      round(np.degrees(np.arctan2(1, 2)), 2))   # the angle of q1 = (2, 1)/sqrt(5)
# 6.0 26.6 1.0 116.6 26.57

# 8. nearly equal eigenvalues: the eigenvalues barely move, the eigenvector turns by 31.7 degrees
eps = delta = 1e-6
for E in (np.diag([1.0, 1.0 + eps]), np.array([[1.0, delta], [delta, 1.0 + eps]])):
    l, V = np.linalg.eigh(E)
    print(np.round((l - [1.0, 1.0 + eps]) * 1e7, 1), round(float(np.degrees(np.arccos(abs(V[1, 1])))), 1))
# [0. 0.] 0.0
# [-6.2  6.2] 31.7

Next#

A general matrix, even a rectangular one, is almost as simple as a symmetric one: it maps one set of perpendicular axes onto another, stretching each by a factor. The next note builds that decomposition, the SVD, from the eigenvectors of the symmetric matrix A⊤AA^\top A, and uses it for rank, low-rank approximation and least squares without a unique solution.

References#

  • M. Rakhuba. Основы матричных вычислений (Foundations of Matrix Computations), lecture course, HSE University, 2025/26. Course page; lecture 2 (normal and positive definite matrices, the SVD) and lecture 12 (LU, LDLᵀ and Cholesky factorizations).
  • G. Strang. Matrix Methods in Data Analysis, Signal Processing, and Machine Learning (MIT 18.065), lecture course, 2018. Lecture 5: positive definite and semidefinite matrices.
  • D. Merkulov. Optimization for ML, lecture course, HSE University, 2024. Course page; lecture 1 (linear algebra review: definite matrices, the spectral decomposition, the Rayleigh bounds).
  • S. Axler. Linear Algebra Done Right, 4th ed. Springer, 2024. Result 2.43 (dimension of a sum of subspaces), 4.12 (the fundamental theorem of algebra) and 7.29 (the real spectral theorem, section 7B).
  • R. A. Horn, C. R. Johnson. Matrix Analysis, 2nd ed. Cambridge University Press, 2013. Sections 4.2 (variational characterizations and subspace intersections) and 4.3 (eigenvalue inequalities for Hermitian matrices).