04 / 16 · Linear Algebra
Determinants and eigenvalues
How much a square matrix scales volume, and which directions it only stretches: the determinant and its computation by elimination, eigenvalues and diagonalization, matrix powers in a Markov chain, and what goes wrong without enough eigenvectors.
On this page 6
Apply the matrix
to again and again: , , . Does grow, shrink or settle? In which direction does it point for large , and how fast does it get there? The entries of do not say. A Markov chain asks the same questions about its distribution after steps, a recurrent network about its gradient after time steps, and gradient descent about its error after iterations.
Unlike the orthogonal matrices of the previous note, a general square matrix stretches some directions, squeezes others and turns most of them. Two kinds of numbers attached to it answer the questions. The determinant says how the map scales volume, and it is zero exactly when the map cannot be undone. The eigenvalues are the stretch factors along the directions that the map does not turn, and in those directions repeated application is the power of a number.
The determinant: how a map scales volume#
A linear map sends the unit square, spanned by and , to the parallelogram spanned by the columns and . Every other square of the grid goes to a shifted copy of the same parallelogram, because . So the map multiplies the area of every grid square, and therefore of every region that the grid approximates, by the same factor. That factor, with a sign that records whether the map keeps or reverses orientation, is the determinant.
The determinant is the factor by which a map scales area
Three properties of signed area pin the determinant down, and they are its definition in any dimension:
- : the unit cube has volume 1.
- is linear in each column when the other columns are fixed. Scaling one edge of a parallelogram by scales its area by , and two parallelograms that share all edges but one, placed side by side, have areas that add.
- is zero when two columns are equal: the parallelogram is flat.
Adding a multiple of one column to another does not change the determinant, by linearity in that column and property 3; geometrically it is a shear, which slides the parallelogram along one edge without changing its area. Swapping two columns flips the sign: expanding by linearity leaves . The sign is the orientation. A positive determinant keeps the turn from to counterclockwise; a negative one makes it clockwise, as a mirror does.
The formula for 2-by-2 matrices#
Expand each column in the standard basis and use linearity. Every term then has either a repeated basis vector, which gives 0, or the two basis vectors in some order, which gives :
The terms and of the expansion vanish by property 3. The three matrices of the figure are
: the unit square becomes a parallelogram of area 10, and the turn from to is still counterclockwise. : the area is 3, and the turn from to is clockwise, so mirrors the plane. : the columns are parallel, the square is flattened onto a segment, and two different points, such as and , land on the same image . has no inverse.
For matrices, expanding all columns in the same way gives the Leibniz formula, a sum of signed products, one per permutation of :
Here , where counts the pairs that puts out of order. The expansion uses only the three properties, so at most one function has them, and the formula itself has them, so exactly one does; both steps are in the folded derivation. The formula is useless for computation: for it has terms.
Derivation: the Leibniz formula
Write column as and expand by linearity in each column in turn:
A term with two equal indices has two equal columns and vanishes by property 3. In every other term the indices form a permutation . Swapping columns two at a time sorts into , and each swap flips the sign. One swap of two entries changes by an odd number (Axler, 2024, 9.34), so every sorting uses a number of swaps with the parity of , and .
Conversely, the formula has the three properties. Each product takes one entry from every column, so the sum is linear in each column; for only the identity permutation survives, giving 1. If columns and are equal, pair each with the permutation that swaps its values at and : the two products are equal, the signs are opposite by the same parity fact, and the sum is 0 (Axler, 2024, 9.32–9.37).
Properties used everywhere#
Each follows from the three properties (Strang, 2011, lecture 18; Axler, 2024, 9.48–9.50 and 9.56). The short ones are proved in the list, the longer ones in the fold after it:
- . Geometrically, the map applies and then , so volumes are scaled by and then by , and two orientation reversals cancel.
- is invertible exactly when , and then , since . If is singular, its columns are dependent, so one column is a combination of the others; subtracting that combination from it leaves a zero column without changing the determinant, and linearity in the zero column, , gives .
- , so everything said about columns holds for rows.
- A triangular matrix has the product of its diagonal as determinant.
- , because each of the columns is scaled. Doubling a matrix multiplies its determinant by 8.
- An orthogonal matrix has , from . The rotation of the plane by has determinant . A Householder reflection has : in a basis of and vectors orthogonal to it is , and a change of basis keeps the determinant, , by the product rule.
Proofs: triangular matrices, products, transposes
Triangular. Let be upper triangular. If some , the first columns lie in the span of , so they are dependent and , the product of the diagonal. Otherwise column 1 is , and subtracting times it from column 2 clears . Working from left to right clears everything above the diagonal without changing the determinant. What remains is , whose determinant is by linearity in each column. A lower triangular matrix is cleared in the same way from the right.
Products. Fix and let . Column of is , so is linear in each column of , vanishes when two columns of are equal, and has . The expansion that gave the Leibniz formula used nothing else, so it gives .
Transposes. If is singular, so is , which has the same rank, and both determinants are 0. Otherwise take ; the permutation matrix is orthogonal, so and , and by the product rule
Transposing a triangular matrix keeps its diagonal, so and . The columns of are distinct standard basis vectors, so by the swap rule, and . The two lines agree.
The determinant of a sum is not the sum of the determinants; there is no rule for it.
Computing a determinant by elimination#
Gaussian elimination turns into an upper triangular matrix with two kinds of row operations. By the transpose rule the column rules hold for rows: adding a multiple of one row to another leaves the determinant unchanged, and a row swap flips its sign. With swaps, the factorization has , (ones on the diagonal) and , the product of the pivots. Taking determinants of both sides,
For
subtracting twice row 1 from row 2 and four times row 1 from row 3 gives the rows , and . Subtracting three times the new row 2 from row 3 gives . No swaps were needed, the pivots are 2, 1 and 2, and . Elimination costs about multiply–adds against the terms of the Leibniz formula: for , about 2,500 instead of .
The log-determinant#
In machine learning the determinant rarely appears alone; its logarithm does. The density of a multivariate Gaussian contains , so its log-likelihood contains minus half of . A normalizing flow pays for every layer, the change-of-variables correction that the multiple integrals note derives. Flows use layers with triangular Jacobians because then the determinant is the product of the diagonal.
The log-determinant is computed as a sum of logarithms of the pivots, never as the logarithm of their product. The determinant of in 1,000 dimensions is , which underflows to 0 in floating point, while its logarithm, , is an ordinary number. NumPy’s slogdet returns the sign and the logarithm for that reason, and Gaussian processes take it from a Cholesky factor, the subject of the next note.
Eigenvectors: directions the map only stretches#
A nonzero vector is an eigenvector of with eigenvalue if
Any nonzero multiple of an eigenvector is again one, so it is the direction that matters, the line through . On that line the map is multiplication by : a stretch for , a squeeze for , a flip for negative , and a collapse to for . Most vectors are turned by the map; the eigenvectors are the exceptions.
Eigenvectors: the directions a map only stretches
The characteristic polynomial#
How do we find the eigenvalues? is one exactly when sends some nonzero vector to zero, that is, when it is singular, and singularity is what the determinant detects:
The second step uses that a square matrix is invertible exactly when its kernel is (matrices note). is a polynomial of degree in , the characteristic polynomial: in the Leibniz formula every entry of is a number or a number minus , so each product has degree at most , and only the product of the diagonal reaches , with the coefficient . The eigenvalues are its roots. Once is known, its eigenvectors are the nonzero vectors of the kernel of , found by elimination. For a matrix,
that is, , where the trace is the sum of the diagonal entries.
For the opening matrix the trace is 7 and the determinant 10, so the characteristic polynomial is , with eigenvalues and . The eigenvectors come from
Both rows of say , so , and indeed . Both rows of say , so , and . The two eigenvectors are not orthogonal, ; for a non-symmetric matrix that is the normal case.
An eigenvector of is also an eigenvector of the matrices built from : if , then , and (Strang, 2016, section 6.1). Apply once more; multiply by , for an invertible , whose eigenvalues are nonzero; add . No other eigenvalues appear, since and, for , . For the opening matrix, has eigenvalues 8 and 5, and has and . The shift is what ridge regression does to : adding raises every eigenvalue by and keeps the eigenvectors. Eigenvalues of a sum or a product of two different matrices follow no such rule.
Not every real matrix has a real eigenvector. The rotation by ,
turns every direction. Its characteristic polynomial is , with roots . By the fundamental theorem of algebra, every polynomial of degree has complex roots counted with multiplicity (Axler, 2024, 4.12–4.13), so every matrix has eigenvalues in . Its proof needs some analysis: grows without bound as , so it has a smallest value, and at a point where a small step always makes smaller, so the smallest value is 0.
A real matrix has its complex eigenvalues in conjugate pairs: conjugating for a polynomial with real coefficients gives (Axler, 2024, 4.14). Each pair describes a rotation within a plane. If with has the eigenvector , the real and imaginary parts of give and : on the plane of and the map is a rotation scaled by . The next note shows that symmetric matrices never have them.
Trace and determinant from the eigenvalues#
Let be the eigenvalues counted with multiplicity, possibly complex. Then
To see why, compare two expansions of , which has leading coefficient 1 and the same roots as . Factored over its roots, which the fundamental theorem of algebra allows, and multiplied out, it is
Expanded by the Leibniz formula, the product of the diagonal entries is one term, and every other term leaves out at least two diagonal entries, so it has at most factors of . A permutation that moves one index moves at least two: if , then , since would contradict that is one-to-one. So
The coefficients of give the trace. For the determinant, set : , and the first expansion gives .
For the opening matrix, and . For the rotation , and . Two consequences follow at once: a matrix is singular exactly when 0 is one of its eigenvalues, and the total variance of a covariance matrix is the sum of its eigenvalues, the identity behind explained variance in PCA.
Diagonalization and matrix powers#
Write the eigenvector equations side by side as the columns of one matrix equation. With and the diagonal , multiplying by on the right scales its columns, so
If the eigenvectors are independent, is invertible, and multiplying by on the right gives : in the basis of its eigenvectors, is diagonal. Every power then reduces to a power of , because each inner is :
and is diagonal with entries . Read from right to left, finds the coordinates of in the eigenvector basis, multiplies the -th by , and goes back:
So, for a diagonalizable , exactly when every (Strang, 2011, lecture 22): tends to 0 exactly when does, and . For the opening example, has the coordinates and in the basis , , and
The opening questions now have answers. grows like , and its direction approaches . The other component shrinks relative to it by the factor , about after 10 steps. The ratio of the second-largest to the largest eigenvalue sets the speed in every iteration of this kind: power iteration for the leading eigenvector, PageRank, and the mixing of Markov chains below. It also explains the vanishing and exploding gradients of recurrent networks, whose gradient through time steps contains factors of the recurrent weight matrix, and why the error of gradient descent on a quadratic shrinks along each eigenvector at its own rate.
Are there always enough independent eigenvectors? Distinct eigenvalues are sufficient, because eigenvectors with different eigenvalues are independent (Axler, 2024, 5.11). For two of them: if , applying gives . Subtracting times the first equation leaves , so , and then .
Proof for any number of eigenvectors
Suppose have distinct eigenvalues and are dependent, with the smallest number for which this happens, so any of them are independent. Take with not all zero. Applying gives
The first vectors are independent, so every , and since the eigenvalues are distinct, . Then forces , a contradiction.
Repeated eigenvalues may or may not come with enough eigenvectors; the last section shows a case where they do not.
Powers of a Markov transition matrix#
The Markov chains note of the probability course models the weather (sunny, cloudy, rainy) with the transition matrix
where row holds the probabilities of moving from state . A distribution over states is a row vector that evolves as . That note stated two facts that diagonalization explains: the distribution converges to the stationary , and the distance to it shrinks like .
Every row of sums to 1, so and 1 is an eigenvalue. A matrix and its transpose have the same characteristic polynomial, since is the transpose of and transposing keeps the determinant, so 1 is also an eigenvalue of . Its eigenvector, written as a row, satisfies : the stationary distribution is a left eigenvector of .
The trace gives , so . Elimination without swaps, as in the section above, gives the pivots , and , so and . The two eigenvalues are therefore the roots of :
As a check, . The three eigenvalues are distinct, so is diagonalizable, and by the formula for applied to and , the distribution after steps is a combination of , and times the left eigenvectors. The first term is the stationary distribution, and it is the only one that survives:
where are the other left eigenvectors and depend on the starting distribution. Why is the first term exactly ? A left eigenvector with eigenvalue has entries summing to 0: with , . Every sums to 1, so the term along the eigenvalue 1 sums to 1, and the only multiple of that does is . The distance to therefore shrinks by a factor approaching per step, whatever the start with . From a sunny day the total absolute difference is at , at and at :
The distance to the stationary distribution shrinks like |λ₂|ᵗ
The gap between 1 and , the spectral gap, decides whether a chain mixes fast or slowly, and MCMC samplers try to keep it large.
Where it breaks#
When diagonalization fails#
The shear
has characteristic polynomial , so its only eigenvalue is 1, a double root. Its eigenvectors form the kernel of
which is the line through alone. The geometric multiplicity of the eigenvalue, the dimension of its eigenvector space, is 1; its algebraic multiplicity, the multiplicity as a root, is 2. There is no basis of eigenvectors, and cannot be diagonalized; this is the standard defective example (Oseledets, 2024, lecture 6).
The eigenvalues then no longer predict the powers. Both eigenvalues of have absolute value 1, yet
grows without bound, linearly in : multiplying by on the right adds the first column to the second, which raises the corner from to .
Every square matrix can still be brought, over , to an almost diagonal form, the Jordan form, with blocks on the diagonal (Axler, 2024, 8.46). In a block of size , has ones just above the diagonal, shifts each basis vector to the previous one, and so has . The proof is beyond this note; the shear is the picture: a repeated eigenvalue short of eigenvectors leaves a chain of vectors that the map pushes into one another. Because and commute, the binomial theorem applies:
The entries are polynomials in of degree below times powers of . So the eigenvalues still decide whether , exactly when every , since (the ratio of consecutive terms tends to ), but only up to such polynomial factors.
Exactly defective matrices are rare in practice, since an arbitrarily small change separates the repeated eigenvalue. Nearly defective ones are common and cause the real trouble. Adding to the corner of gives distinct eigenvalues 1 and , the diagonal entries of a triangular matrix, since by the triangular rule, with eigenvectors and , almost parallel. For the condition number of is , and , computed from a nearly singular basis, loses about eight digits in floating point, a relative error of about with the rounding unit ; the conditioning note derives this bound. Symmetric matrices avoid the problem with an orthonormal basis of eigenvectors (next note), and every matrix has a decomposition with orthonormal bases on both sides, the singular value decomposition.
The determinant does not measure near-singularity#
in 100 dimensions, yet is as easy to invert as . The matrix with rows and has a determinant of about too, and it is nearly singular: a change of in one entry makes it singular. A small determinant can come from scale alone. The right measure is the condition number of the conditioning note, the ratio of the largest to the smallest singular value: 1 for , and for the second matrix.
Eigenvalues are not computed from the polynomial#
The characteristic polynomial is a tool for proofs and small examples. For there is no general formula for the roots of a polynomial in radicals, the Abel–Ruffini theorem of Galois theory: such a formula exists only when the group of permutations of the roots that respect their algebraic relations is solvable, and for it need not be. Every polynomial with leading coefficient is the characteristic polynomial of some matrix, its companion matrix, so no such formula can give the eigenvalues of every matrix, and every eigenvalue algorithm is iterative (Trefethen and Bau, 1997, lecture 25). The roots of the characteristic polynomial are also badly conditioned functions of its coefficients. The diagonal matrix with entries has eigenvalues , which an eigenvalue routine returns exactly. Its characteristic polynomial has coefficients up to about , which double precision rounds, and the roots of the rounded polynomial are off by up to . Libraries work on the matrix itself, with the QR algorithm.
What you should remember#
- is the signed factor by which scales volume, in 2D; it is zero exactly when is singular, and .
- Compute it by elimination, as times the product of the pivots, and use the log-determinant in likelihoods.
- Eigenvalues are the roots of ; is their sum and their product.
- With independent eigenvectors, and ; distinct eigenvalues guarantee it.
- The largest dominates , and sets the speed; a Markov chain approaches like .
- A shear has one eigenvector for a double eigenvalue, and its powers grow although .
Code#
The note’s examples checked with NumPy: the determinant by elimination against the library, the log-determinant that does not underflow, the eigenvalues, trace and determinant identities, shifts and powers, matrix powers through diagonalization, the weather chain, and the three failures. It runs in well under a second; exact digits in the last places can differ across platforms and library versions.
import math
import numpy as np
# 1. 2x2 determinants: area 10, a mirror with -3, a flattened square with 0
A = np.array([[4.0, 1.0], [2.0, 3.0]])
C = np.array([[1.0, 2.0], [2.0, 1.0]])
D = np.array([[2.0, 1.0], [4.0, 2.0]])
print([round(float(np.linalg.det(m)), 6) for m in (A, C, D)])
# [10.0, -3.0, 0.0]
# 2. the determinant from the pivots of elimination with partial pivoting: (-1)^swaps times their product
def det_by_elimination(M):
U = M.astype(float).copy(); n = len(U); sign = 1.0
for k in range(n):
p = k + np.argmax(np.abs(U[k:, k])) # the largest pivot candidate, for stability
if U[p, k] == 0: return 0.0
if p != k: U[[k, p]] = U[[p, k]]; sign = -sign
U[k + 1:] -= np.outer(U[k + 1:, k] / U[k, k], U[k])
return sign * np.prod(np.diag(U))
M = np.array([[2.0, 1.0, 1.0], [4.0, 3.0, 3.0], [8.0, 7.0, 9.0]])
rng = np.random.default_rng(0)
R = rng.normal(size=(6, 6))
print(round(det_by_elimination(M), 6), round(det_by_elimination(R), 6), round(float(np.linalg.det(R)), 6))
# 4.0 -2.340511 -2.340511
# (the hand elimination of the note used no swaps; partial pivoting swaps rows but the determinant is the same)
print(sum((20 - k) ** 2 for k in range(1, 20)), f'{math.factorial(20):.1e}') # 2470 2.4e+18: elimination against Leibniz
# 3. properties: products, transposes, scaling, inverses
B = rng.normal(size=(6, 6))
print(np.isclose(np.linalg.det(R @ B), np.linalg.det(R) * np.linalg.det(B)),
np.isclose(np.linalg.det(R.T), np.linalg.det(R)),
np.isclose(np.linalg.det(2 * R), 2**6 * np.linalg.det(R)),
np.isclose(np.linalg.det(np.linalg.inv(R)), 1 / np.linalg.det(R)))
# True True True True
# 4. the determinant underflows, the log-determinant does not
S = 0.1 * np.eye(1000)
sign, logdet = np.linalg.slogdet(S)
print(np.linalg.det(S), float(sign), round(float(logdet), 4))
# 0.0 1.0 -2302.5851
# 5. eigenvalues and eigenvectors of A; trace = sum and det = product, also for a random matrix
lam, V = np.linalg.eig(A)
lam, V = lam.real, V.real # real here; NumPy may return a complex type
print(lam, (V / V[0]).round(6).T.tolist()) # eigenvectors scaled so their first entry is 1
print(np.isclose(lam.sum(), np.trace(A)), np.isclose(lam.prod(), np.linalg.det(A)))
lr = np.linalg.eigvals(R) # complex in general, in conjugate pairs
print(np.isclose(lr.sum(), np.trace(R)), np.isclose(lr.prod(), np.linalg.det(R)), np.iscomplexobj(lr))
# [5. 2.] [[1.0, 1.0], [1.0, -2.0]]
# True True
# True True True
# shifts and inverses keep the eigenvectors and move the eigenvalues
print(np.sort(np.linalg.eigvals(A + 3 * np.eye(2)).real), np.sort(np.linalg.eigvals(np.linalg.inv(A)).real))
# [5. 8.] [0.2 0.5]
# 6. powers through diagonalization: A^k x = V Lambda^k V^-1 x, and A^3 x = (86, 78)
x = np.array([1.0, 0.0])
c = np.linalg.solve(V, x)
for k in (3, 10):
print(k, np.linalg.matrix_power(A, k) @ x, (V @ (lam**k * c)).round(6))
print((np.linalg.solve(np.array([[1.0, 1.0], [1.0, -2.0]]), x)).round(6)) # coordinates in the basis (1, 1), (1, -2)
# 3 [86. 78.] [86. 78.]
# 10 [6510758. 6509734.] [6510758. 6509734.]
# [0.666667 0.333333]
# 7. the weather chain: eigenvalues, the stationary distribution, and convergence like 0.473^t
P = np.array([[0.7, 0.2, 0.1], [0.3, 0.4, 0.3], [0.2, 0.3, 0.5]])
mu, W = np.linalg.eig(P.T) # left eigenvectors of P
order = np.argsort(-np.abs(mu)); mu, W = mu[order].real, W[:, order].real
pi = W[:, 0] / W[:, 0].sum()
print(mu.round(4), (0.3 + np.sqrt(0.03)).round(4), round(float(np.linalg.det(P)), 6), (pi * 46).round(6))
p, dist = np.array([1.0, 0.0, 0.0]), []
for t in range(21):
dist.append(np.abs(p - pi).sum()); p = p @ P
print([f'{dist[t]:.3g}' for t in (0, 1, 2, 10, 20)], round(dist[20] / dist[19], 4))
# [1. 0.4732 0.1268] 0.4732 0.06 [21. 13. 12.]
# ['1.09', '0.487', '0.227', '0.000567', '3.19e-07'] 0.4732
# 8. the shear: one eigenvector for a double eigenvalue, and powers that grow although |lambda| = 1
J = np.array([[1.0, 1.0], [0.0, 1.0]])
print(np.linalg.eigvals(J).real, np.linalg.matrix_rank(J - np.eye(2)), np.linalg.matrix_power(J, 50).tolist())
eps = 1e-8
lam_e, V_e = np.linalg.eig(np.array([[1.0, 1.0], [0.0, 1.0 + eps]]))
print(lam_e.real, f'{np.linalg.cond(V_e):.2g}') # nearly parallel eigenvectors: V is nearly singular
# [1. 1.] 1 [[1.0, 50.0], [0.0, 1.0]]
# [1. 1.00000001] 2e+08
# 9. a small determinant is not near-singularity; the condition number is
N = np.array([[1.0, 1.0], [1.0, 1.0 + 1e-12]])
print(f'{np.linalg.det(0.1 * np.eye(100)):.0e} {np.linalg.cond(0.1 * np.eye(100)):.0f} {np.linalg.det(N):.0e} {np.linalg.cond(N):.0e}')
# 1e-100 1 1e-12 4e+12
# 10. eigenvalues from the characteristic polynomial: rounding its coefficients moves the roots
lam20 = np.arange(1.0, 21.0)
roots = np.sort(np.roots(np.poly(lam20)).real)
print(f'{np.abs(np.poly(lam20)).max():.1e}', round(np.abs(roots - lam20).max(), 3), np.abs(np.sort(np.linalg.eigvals(np.diag(lam20)).real) - lam20).max())
# 1.4e+19 0.039 0.0
Next#
The eigenvectors of the opening matrix were not orthogonal, the rotation had none in real space, and the shear had too few. The matrices that machine learning builds most often, covariance matrices, Hessians, kernel matrices and , have none of these problems because they are symmetric. The next note proves that a symmetric matrix always has real eigenvalues and an orthonormal basis of eigenvectors, and uses them to read the shape of a quadratic form, to test positive definiteness and to find the directions of largest and smallest curvature.
References#
- G. Strang. Introduction to Linear Algebra, 5th ed. Wellesley-Cambridge Press, 2016. Section 6.1 (introduction to eigenvalues: , trace and determinant checks, powers, shifts and inverses).
- G. Strang. 18.06SC Linear Algebra, MIT OpenCourseWare, 2011. Lecture summaries: properties of determinants (lecture 18) and diagonalization and powers of A (lecture 22).
- S. Axler. Linear Algebra Done Right, 4th ed. Springer, 2024 (open access). 4.12–4.14 (the fundamental theorem of algebra; real polynomials have nonreal zeros in pairs), section 5A, 5.11 (eigenvectors of distinct eigenvalues are independent), 8.46 (Jordan form), section 9C, 9.32–9.37 (the sign of a permutation and the formula for alternating forms), 9.48–9.50 and 9.56 (triangular matrices, products, invertibility, transposes), 9.61 (the volume factor ).
- L. N. Trefethen, D. Bau III. Numerical Linear Algebra. SIAM, 1997. Lecture 25 (overview of eigenvalue algorithms: why every eigenvalue solver must be iterative).
- I. Oseledets. Numerical Linear Algebra, course notebooks, 2024. Lecture 6 (eigenvalues and eigenvectors, diagonalizability and the defective matrix with a double eigenvalue, PageRank as an eigenproblem).