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:
All their coefficients are positive, and they look alike. Yet is positive for every , a bowl with its minimum at the origin, while : is a saddle that goes down in some directions. The cross term 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 with a symmetric matrix, . For the cross coefficient 4 is split equally between the two off-diagonal entries:
Nothing is lost by insisting on symmetry. A number equals its transpose, so for any square , and averaging the two gives : only the symmetric part of a matrix enters its quadratic form. Covariance matrices, the Gram matrix 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 there is an orthogonal matrix () with columns , and a real diagonal , such that
Both halves of the proof use one property: a symmetric matrix moves from one side of an inner product to the other, .
Real eigenvalues#
Let for a vector , , and a number that may a priori be complex; is the entrywise complex conjugate. Look at the number and take its conjugate:
A number equal to its conjugate is real. The same number is , and is positive, so
The eigenvector can be chosen real as well: with and , real, the real and imaginary parts of give and , and , are not both zero.
Orthogonal eigenvectors#
Let and with . Move across the inner product:
So , and since , the eigenvectors are orthogonal.
Proof of the full theorem, including repeated eigenvalues
By induction on ; for 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 with eigenvalue . Let be the subspace of vectors orthogonal to , of dimension . maps into itself: for , .
Put an orthonormal basis of into the columns of . The matrix is symmetric of size , so by the induction hypothesis with orthogonal. The columns of are orthonormal, lie in , and are eigenvectors of : , where because the columns of lie in and is the orthogonal projection onto . Together with they form an orthonormal eigenbasis of . As columns of they give , and multiplying on the right by gives .
A repeated eigenvalue therefore never lacks eigenvectors. The characteristic polynomial is , so an eigenvalue of multiplicity sits times on the diagonal of . In eigen-coordinates, forces wherever , so the matching columns of 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. has the columns , and a matrix with columns times a matrix with rows is . Each is the orthogonal projection onto the line through . So projects onto each eigen-axis, scales the projection by and adds the results.
Example. For our the trace is 7 and the determinant 6, so the characteristic polynomial is . The null space of is spanned by , and that of by . Their inner product is , as the theorem promises, and after normalization and . The rank-one terms add up to :
Orthonormality makes the eigen-coordinates free. For the non-symmetric matrix of the previous note, the coordinates of in the eigenbasis needed a linear solve, . Here , so the coordinates are inner products, , and lengths are kept: , because a square with also has .
Functions of the matrix act on the eigenvalues alone: , when no is zero, and when none is negative. Each is checked by multiplying out, with cancelling in the middle: . Whitening a Gaussian with , in the multivariate Gaussian note, is the last of these.
Quadratic forms and their level sets#
The quadratic form of is . In the eigen-coordinates it loses its cross terms:
Every question about the shape of is now a question about the signs and sizes of the .
If all and , the level set is
an ellipse in two dimensions and an ellipsoid in more. Its axes point along the eigenvectors , with half-length along . A large eigenvalue means a steep direction and a short axis: the function reaches the level 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 , in the coordinates and , the function is . The level set is an ellipse with half-length along and along ; the level set is the same ellipse scaled by 2. For , with matrix , the eigenvalues are 3 along and along . So : up along one diagonal, down along the other, the saddle of the opening.
Level sets of a quadratic form and the eigen-axes of its matrix
Every quadratic loss has these level sets around its minimum. The function with all has gradient (the quadratic case), which vanishes at . Put , multiply out the brackets, and use , a number equal to its transpose:
The level sets are ellipses centred at the minimum, shaped by the eigenvalues of . Least squares is this function with (the normal equations), and near a minimum every smooth loss looks like it, with 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 , whose eigenvalues are . That is why the half-axes of a covariance ellipse are , where those of would be .
Positive definite and semidefinite matrices#
A symmetric matrix is positive definite, , if for every , and positive semidefinite, , if for every . 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 . Four finite tests are equivalent to it for a symmetric :
The eigenvalue test follows from the eigen-coordinates. with , and maps nonzero vectors to nonzero vectors. If every , the sum is positive as soon as one is nonzero. Conversely, gives and the value , which must then be positive.
The factored form works in both directions. If , then , with equality only when , which independent columns allow only for . If all , then does the job.
The -th leading minor is the determinant of the top-left block . On a positive definite matrix elimination needs no row swap, its -th pivot is (with ), 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 , , with zeros to . Then , so , its eigenvalues are positive, and , their product, is positive.
Positive minors give . By induction on : let with lower triangular and a positive diagonal. Split off the last row and column of :
holds exactly when , a triangular solve for , and . Taking determinants, , so and is real and positive. With invertible, for , and by the factored-form test.
Pivots. Elimination without swaps adds multiples of earlier rows to later ones. On the first rows and columns these are row operations on , which keep . After steps that block is upper triangular with the pivots on its diagonal, so and . 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 and , is ? The definition answers at once, ; the eigenvalues of a sum are not the sums of eigenvalues.
- Is ? The eigenvalues answer: they are .
- Is for an orthogonal ? The definition again, with : .
- 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 has only positive entries and is a saddle. And a positive definite matrix may have negative entries: has eigenvalues 1 and 3.
The two examples, and the boundary between them#
| leading minors | , | , |
| pivots | , | , |
| eigenvalues | , | , |
| verdict | positive definite | indefinite |
Every test agrees, and the pivots multiply to the minors: .
Semidefinite matrices sit on the boundary. Replace the corner entry 2 of by . The second leading minor is , so gives a bowl. For the determinant is negative: a saddle. At the eigenvalues are and : a trough, flat along . In floating point the boundary blurs: NumPy’s Cholesky accepts this matrix, because rounding leaves its second pivot at about instead of 0.
For semidefiniteness the eigenvalue and tests carry over with , and may have dependent columns. The leading minors do not. For both leading minors are 0, none is negative, and still . 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 to the coordinates of a subset, as for above, makes every principal submatrix of semidefinite, with determinant . Conversely, column of is . The determinant is linear in each column, so it splits into a sum over the sets of columns that take , and each term is times the principal minor on the other indices. With all principal minors , the polynomial is positive for every , so no equals .
Why covariance and kernel matrices are positive semidefinite#
A covariance matrix, for a random vector with mean , gives for any fixed vector
The quadratic form of a covariance is the variance of a projection. It is zero exactly when some combination is constant. For a semidefinite , vanishes exactly when , so is singular exactly when lies in a hyperplane with probability 1.
The sample covariance of centred data is of the form . With no more points than dimensions, , it is singular. Centring makes the rows of sum to zero, so has rank at most , and has the null space of ( gives ), hence the same rank; PCA in high dimension works with such matrices (dimensionality reduction).
A kernel evaluated on points gives , where has the rows . Then . 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, , and of logistic regression, with positive weights in the diagonal , 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: has the eigenvectors of and the eigenvalues . Ridge regression (), the noise term of a Gaussian process () and the small jitter added before a Cholesky factorization all do this.
The Cholesky factorization#
To sample from or to solve 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, , at the price of an iterative algorithm. A triangular one is cheaper. Every factors as with lower triangular and , as the proof of the tests above showed.
To find , write the entry of for . Only contribute, since for :
For the last term is , and for we divide by :
Column by column, everything on the right is already known. The first rows of depend only on , and the quantity under the root at step is the of the proof above, the -th pivot. If is not positive definite, some ; at the first such the earlier steps succeed and this quantity is , so the algorithm stops. That makes it the cheapest numerical test of definiteness. Column computes entries, each with an inner product of length ; the sum is multiply–adds, half of the of LU, with no row swaps (Rakhuba, 2025, lecture 12).
Example. For
the three columns of come out as follows:
| column | computation | entries |
|---|---|---|
| 1 | , , | |
| 2 | , | |
| 3 |
So
and the determinant comes with it:
Sampling from a Gaussian goes through this factor: if , then , the recipe of the multivariate Gaussian note. So does solving with a kernel matrix: becomes two triangular systems, and , each in about multiply–adds, with for free; this is how Gaussian process regression computes its posterior and marginal likelihood without forming .
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 on 50 equally spaced points of . Cholesky with 150 significant digits succeeds, so the matrix is positive definite, but its last pivot is , and is smaller still. That pivot is , because and the last column of the triangular is ; by the Rayleigh bound below, .
Rounding the entries to double precision changes by some with , where , and by Weyl’s inequality below that can move every eigenvalue by as much. The computed smallest eigenvalue is , the largest 38.3, and double-precision Cholesky fails. The jitter makes it succeed, at the price of a slightly different matrix.
The Rayleigh quotient: the extreme directions#
How large can 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 , for , asks the same question without fixing the length.
In eigen-coordinates, with , the quotient is an average of the eigenvalues:
with weights that are non-negative and sum to 1. An average lies between its smallest and its largest term:
All the weight sits on when is its eigenvector, so the bound is reached there, and likewise for .
Example. For and , . In eigen-coordinates , so the weights are and , and . On the unit circle the quotient is
by the double-angle formulas. Its amplitude is , so it oscillates between and with period , and peaks where , at , the direction of :
The Rayleigh quotient on the unit circle
The first principal component maximizes the variance over unit vectors , a Rayleigh quotient of the covariance, so it is the top eigenvector (PCA as variance maximization). For any matrix , , so the largest factor by which stretches a vector is , the spectral norm; the next note builds the SVD on this observation.
Along a unit direction , the second derivative of a function with Hessian is , which lies between the extreme eigenvalues of . Gradient descent with step is stable only if , and the ratio , 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 and read off , 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 , the Courant–Fischer theorem says that the -th one is the best worst-case Rayleigh quotient over -dimensional subspaces:
The span of attains the maximum: on it, is an average of , so its minimum is . No other -dimensional subspace does better. It must contain a unit vector orthogonal to , because a subspace of dimension and the span of , of dimension , intersect: (Axler, 2024, 2.43). On such a vector is an average of , at most .
Two related facts are used in machine learning. The first is PCA with components. For with orthonormal columns, the variance kept is
The weights lie in , because is the orthogonal projection onto the columns of , and sum to . Such a sum is largest with weight 1 on the largest , and attains it.
The second is Weyl’s inequality: for symmetric and , . Since has the eigenvalues , and . Hence for every . The max–min over -dimensional subspaces keeps the inequality, so , and exchanging with gives the other side (Horn and Johnson, 2013, sections 4.2 and 4.3). A sample covariance tends to entrywise by the law of large numbers, and , 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 and
whose eigenvectors are and , and add to both off-diagonal entries. The eigenvalues move by each, within as Weyl promises. The eigenvector of the larger one turns by . With ten times larger it would turn by , almost .
The angle comes from a rotation. For a symmetric matrix with entries , the rotation by has the eigenvectors as columns when the off-diagonal entry of vanishes:
so . Here and , which gives the angle above.
The angle is set by the ratio of the perturbation to the gap between the eigenvalues, here . Only the eigenspace of a cluster of close eigenvalues is well determined; for 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. 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, , and call a symmetric solver such as numpy.linalg.eigh. The full decomposition costs , out of reach for a kernel matrix on 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: .
- In , ; for the level set has half-axes along .
- iff all eigenvalues, pivots or leading minors are positive, iff with independent columns; for leading minors are not enough.
- Covariance, Gram and kernel matrices are , hence semidefinite; makes them definite.
- Cholesky costs multiply–adds, samples Gaussians as , and gives .
- ; 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 , 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).