linearly

Lecture 14

Determinants

One number says how much a matrix inflates or flattens space. Every rule, every formula, and every use of the determinant comes out of that.

65 slides / MIT 18.06, Lectures 18 to 20 / Strang Ch. 5

Slide 1 of 65
1 / 65

The idea in one sentence

The determinant of a square matrix is the factor by which that matrix scales volume, and it is zero exactly when the matrix flattens space.

The number you have already dragged

In Lecture 2 you watched a machine with columns (2,0)(2, 0) and (1,1)(1, 1) pick up the unit square and put it down as a parallelogram. Underneath the picture a small readout said detA=2\det A = 2. Here is what it was telling you.

A=[2101]A = \begin{bmatrix} 2 & 1 \\ 0 & 1 \end{bmatrix}

The unit square has area 1. Its image has area 2. That is the whole content of the number: feed the machine any region, and whatever area went in comes out multiplied by detA\det A. In three dimensions the same number multiplies volume. Nothing about the shape of the region matters, which is the surprising part. A square or a circle or the outline of a country all scale by the same factor, because a linear map treats every small patch of the plane the same way.

column 1column 2column 2column 1area 2area 2det = +2det = −2
Fig. 1 

The dashed square is where you start. The same two arrows give the same patch either way round, so the area is 2 in both pictures. The small curved arrow shows the difference: on the left it turns counterclockwise from column 1 to column 2, on the right it turns clockwise. That turn is the sign.

So the determinant carries one number and one bit. The number detA|\det A| is the volume factor. The sign says whether the machine kept the handedness of space or turned it over, the way a mirror does. And when the columns line up, the parallelogram has no area at all, the machine has crushed the plane onto a line, and the determinant is zero. Zero determinant means singular, which is the test this whole course has been circling.

c₁c₂c₃c₁c₂c₃det = 6, the box holds volume 6det = 0, the box holds nothing
Fig. 2 

The same idea one dimension up. Three columns span a box, and its volume is the determinant. Slide the third column down into the plane of the other two, as on the right, and the box has no thickness left. Its volume, and the determinant, are zero. That is what singular looks like.

Drag the two columns together and watch the number die:

Try it. Drag the two columns and watch the area

column 1 = (2.0, 0.0)
column 2 = (1.0, 1.0)

det A = 2.00

Area 2.00, orientation kept. The corner order still runs counterclockwise.

Drag one column onto the other. The patch thins, the number falls to zero, and the square has been crushed onto a line.

Three rules

You could define the determinant by a formula. It is better to define it by what it does, because then the formulas can be derived instead of memorized. Three rules are enough.

Rule 1. detI=1\det I = 1. The identity does nothing, so the unit box keeps its volume.

Rule 2. Exchanging two rows reverses the sign. Swapping two edges of the box turns it inside out and the volume factor changes sign.

Rule 3. The determinant is linear in each row separately, with the other rows held still. Two halves:

tatbcd=tabcd,a+ab+bcd=abcd+abcd.\begin{vmatrix} ta & tb \\ c & d \end{vmatrix} = t\begin{vmatrix} a & b \\ c & d \end{vmatrix}, \qquad \begin{vmatrix} a + a' & b + b' \\ c & d \end{vmatrix} = \begin{vmatrix} a & b \\ c & d \end{vmatrix} + \begin{vmatrix} a' & b' \\ c & d \end{vmatrix}.

The first half is stretching one edge of the box while the others stay put, which multiplies the volume by tt. The second half is hard to see in words and immediate in a picture.

(3, 0)(1, 2)(4, 2)(0, 2)(0, 2)(0, 2)628+=the second row is the same in all three, and (3, 0) + (1, 2) = (4, 2)
Fig. 3 

Linearity in the first row, drawn. Three parallelograms share the dashed edge (0,2)(0, 2). Add the two solid edges and the areas add: 6+2=86 + 2 = 8. The shared edge is the base, and area is base times height, so adding heights adds areas.

Now use the rules. Rule 3 says scaling one row scales the determinant, so scaling every row of a 2×22 \times 2 matrix scales it twice:

det(2I)=2002=21002=221001=4.\det(2I) = \begin{vmatrix} 2 & 0 \\ 0 & 2 \end{vmatrix} = 2\begin{vmatrix} 1 & 0 \\ 0 & 2 \end{vmatrix} = 2 \cdot 2 \begin{vmatrix} 1 & 0 \\ 0 & 1 \end{vmatrix} = 4 .

Pull the 2 out of row one, then out of row two, then apply Rule 1. In nn dimensions the same argument gives det(tI)=tn\det(tI) = t^n, which is the statement that doubling every edge of a box in three dimensions multiplies its volume by 8. This is the one place where det(2I)=2detI\det(2I) = 2\det I looks right and is not. Linear in each row separately does not mean linear in the matrix.

What falls out

Everything else is a consequence. Each one is worth checking on a 2×22 \times 2 before you trust it in general.

Two equal rows give zero. Swap the two equal rows. The matrix is unchanged, so its determinant is unchanged. Rule 2 says the determinant flipped sign. The only number equal to its own negative is 0:

3535=1515=0.\begin{vmatrix} 3 & 5 \\ 3 & 5 \end{vmatrix} = 15 - 15 = 0 .

Geometrically the two edges point the same way, so the box is flat.

A row of zeros gives zero. Scale that row by t=0t = 0 and use Rule 3.

Elimination changes nothing. Subtracting a multiple of one row from another leaves the determinant alone:

3112=5,31053=5.\begin{vmatrix} 3 & 1 \\ 1 & 2 \end{vmatrix} = 5, \qquad \begin{vmatrix} 3 & 1 \\ 0 & \tfrac{5}{3} \end{vmatrix} = 5 .

Rule 3 splits the changed row into the original plus a multiple of the row you subtracted, and the second piece is a matrix with two proportional rows, which is zero. In pictures it is a shear.

row 1 = (3, 1)row 2 = (1, 2)row 2 − ⅓ row 1row 2 slides along the dotted line, parallel to row 1both parallelograms have area 5
Fig. 4 

Elimination slides one edge of the box along a line parallel to the other edge. The base does not move and the height does not change, so neither does the area. This is why you can run elimination first and read the determinant off the result.

A triangular matrix is the product of its diagonal. Pull each diagonal entry out of its row with Rule 3, clear the off-diagonal entries with elimination, and land on detI=1\det I = 1:

ab0d=ad,242011004=214=8.\begin{vmatrix} a & b \\ 0 & d \end{vmatrix} = ad, \qquad \begin{vmatrix} 2 & 4 & -2 \\ 0 & 1 & 1 \\ 0 & 0 & 4 \end{vmatrix} = 2 \cdot 1 \cdot 4 = 8 .

Singular means zero. If AA is singular, elimination produces a row of zeros, so detA=0\det A = 0. If AA is invertible, elimination produces nonzero pivots all the way down, so detA0\det A \neq 0. One number decides invertibility, which is what makes the determinant worth having at all.

Determinants multiply. det(AB)=(detA)(detB)\det(AB) = (\det A)(\det B). Volume factors compose: do one machine then the other and the scalings multiply. Take AA with rows (3,1)(3, 1) and (1,2)(1, 2), and BB with rows (0,2)(0, 2) and (1,4)(-1, 4). Their determinants are 5 and 2, the product ABAB has rows (1,10)(-1, 10) and (2,10)(-2, 10), and its determinant is 10. One corollary drops out at once: AA1=IAA^{-1} = I forces det(A1)=1/detA\det(A^{-1}) = 1/\det A.

area 1area 5area 10ABdet B times det A = 2 × 5 = 10 = det BA
Fig. 5 

Volume factors compose. The unit square has area 1. The machine AA multiplies it by 5. The machine BB multiplies whatever it is handed by 2. Run them one after the other and the areas multiply, which is the whole content of det(AB)=detAdetB\det(AB) = \det A \det B.

Transposing changes nothing. det(AT)=detA\det(A\T) = \det A. That is why every rule stated for rows is equally true for columns, and why the column pictures in this lecture were legitimate all along.

python
import numpy as np

A = np.array([[2., 4., -2.],
              [4., 9., -3.],
              [-2., -3., 7.]])       # the elimination example from Lecture 4
r = lambda x: round(float(x), 9)     # det comes out of elimination: it rounds

print(r(np.linalg.det(A)))                     # 8.0
print(r(np.linalg.det(A[[1, 0, 2]])))     # -8.0   a row swap flips the sign

E = A.copy()
E[1] = E[1] - 2 * E[0]               # exactly what elimination does
E[2] = E[2] + E[0]
print(r(np.linalg.det(E)))                     # 8.0    unchanged

U = np.array([[2., 4., -2.], [0., 1., 1.], [0., 0., 4.]])
print(r(np.prod(np.diag(U))))            # 8.0    the pivots multiply to it

D = A.copy(); D[2] = D[0]            # make two rows equal
print(r(np.linalg.det(D)))                     # 0.0    flat

B = np.array([[0., 2., 1.], [1., 1., 0.], [3., 0., 1.]])
print(r(np.linalg.det(A @ B)))                 # -40.0
print(r(np.linalg.det(A) * np.linalg.det(B)))  # -40.0   the same
print(r(np.linalg.det(A.T)))                   # 8.0    same as det A

The determinant your computer actually computes

Put two of those consequences side by side. Elimination does not change the determinant, and a triangular matrix is the product of its diagonal. So run elimination, then multiply the pivots. That is the whole algorithm, and it is what every library does.

Take the elimination example from Lecture 4:

A=[242493237]    U=[242011004],detA=214=8.A = \begin{bmatrix} 2 & 4 & -2 \\ 4 & 9 & -3 \\ -2 & -3 & 7 \end{bmatrix} \;\longrightarrow\; U = \begin{bmatrix} 2 & 4 & -2 \\ 0 & 1 & 1 \\ 0 & 0 & 4 \end{bmatrix}, \qquad \det A = 2 \cdot 1 \cdot 4 = 8 .

The pivots were 2, 1, 4 when you first met them, and their product is the determinant. If elimination needed row exchanges, count them: PA=LUPA = LU gives detA=±d1d2dn\det A = \pm d_1 d_2 \cdots d_n, with the sign fixed by whether the number of exchanges was even or odd.

The tridiagonal matrix from Lecture 5 makes the same point. Its pivots were 22, 32\tfrac{3}{2}, 43\tfrac{4}{3}, and they multiply to 4:

K=[210121012],detK=23243=4.K = \begin{bmatrix} 2 & -1 & 0 \\ -1 & 2 & -1 \\ 0 & -1 & 2 \end{bmatrix}, \qquad \det K = 2 \cdot \tfrac{3}{2} \cdot \tfrac{4}{3} = 4 .

One more reading of the same fact. The kk-th pivot is a ratio of determinants:

dk=detAkdetAk1,d_k = \frac{\det A_k}{\det A_{k-1}} ,

where AkA_k is the top-left k×kk \times k corner of AA. The product telescopes, which is the formula above run backwards.

Cost: elimination is about n3/3n^3/3 operations, so a 1000×10001000 \times 1000 determinant takes a fraction of a second. Hold that number. It is about to be worth a great deal.

Counting every term honestly

Pivots are excellent for computing and useless for seeing structure. They are ratios of things that came out of elimination, and you cannot look at them and see the original entries aija_{ij}. So derive a formula that uses the entries directly, from the three rules alone.

Split each row into its coordinate pieces and expand by linearity. For a 3×33 \times 3 matrix each row splits three ways, giving 27 terms, but any term that picks two entries from the same column has two proportional rows and dies. What survives is one entry from each row and one from each column. Count those: three choices for row one, two left for row two, one for row three. Six terms, or n!n! in general.

Each surviving term is a signed product, and the sign comes from Rule 2. Write the column numbers in row order; the sign is ++ if that ordering can be sorted back to 1,2,31, 2, 3 with an even number of swaps, and - if odd.

+a₁₁a₂₂a₃₃= +126+a₁₂a₂₃a₃₁= +24+a₁₃a₂₁a₃₂= +24a₁₁a₂₃a₃₂= −18a₁₂a₂₁a₃₃= −112a₁₃a₂₂a₃₁= −36126 + 24 + 24 − 18 − 112 − 36 = 8
Fig. 6 

All six terms of a 3×33 \times 3 determinant, for the matrix above. Each grid marks one entry per row and one per column, which is what “no two from the same column” leaves. The numbers add to 8, the same 8 the pivots gave.

In general this is the big formula:

detA=σsign(σ)a1σ(1)a2σ(2)anσ(n),\det A = \sum_{\sigma} \operatorname{sign}(\sigma)\, a_{1\sigma(1)} a_{2\sigma(2)} \cdots a_{n\sigma(n)} ,

summing over all n!n! orderings σ\sigma of the columns. It is a real formula, it is exact, and nobody computes with it. Here is why, measured on one laptop:

python
import numpy as np, time
from itertools import permutations

def sign(p):
    s = 1
    for i in range(len(p)):
        for j in range(i + 1, len(p)):
            if p[i] > p[j]: s = -s
    return s

def big_formula(A):
    n = len(A)
    return sum(sign(p) * np.prod([A[i, p[i]] for i in range(n)])
               for p in permutations(range(n)))

rng = np.random.default_rng(0)
for n in [3, 8, 10, 11]:
    A = rng.standard_normal((n, n))
    t = time.perf_counter(); d1 = big_formula(A)
    big = time.perf_counter() - t
    t = time.perf_counter(); d2 = np.linalg.det(A)
    lu = time.perf_counter() - t
    print(n, f"{big:9.4f}s", f"{lu:.6f}s", abs(d1 - d2) < 1e-9)
#  3      0.0000s 0.000043s True
#  8      0.1253s 0.000023s True         40,320 terms
# 10     12.8782s 0.000030s True      3,628,800 terms
# 11    153.1656s 0.000115s True     39,916,800 terms, at 11 by 11

Two and a half minutes against a tenth of a millisecond, and the gap grows by a factor of nn every time you add a row. Your machine will print different seconds; the shape of the table is what matters. At n=20n = 20 the big formula needs 2.4×10182.4 \times 10^{18} terms, which at the rate measured above is about three hundred thousand years. Elimination on the same matrix needs about 2700 operations.

Cofactors, or the same sum folded

The six terms have a pattern. Group them by which entry they took from the first row:

detA=a11(a22a33a23a32)a12(a21a33a23a31)+a13(a21a32a22a31).\det A = a_{11}(a_{22}a_{33} - a_{23}a_{32}) - a_{12}(a_{21}a_{33} - a_{23}a_{31}) + a_{13}(a_{21}a_{32} - a_{22}a_{31}) .

Every bracket is a 2×22 \times 2 determinant, and each one is what remains of AA after deleting row 1 and the column that a1ja_{1j} came from. That leftover determinant is the minor M1jM_{1j}, and with its sign attached it is the cofactor:

Cij=(1)i+jMij.C_{ij} = (-1)^{i+j} M_{ij} .

The signs form a checkerboard starting with ++ in the top-left corner. Expanding along any row gives detA=ai1Ci1+ai2Ci2++ainCin\det A = a_{i1}C_{i1} + a_{i2}C_{i2} + \cdots + a_{in}C_{in}, which is worth doing by hand when a row is mostly zeros. For the matrix above, along the first row:

2933744327+(2)4923=2(54)4(22)2(6)=8.2\begin{vmatrix} 9 & -3 \\ -3 & 7\end{vmatrix} - 4\begin{vmatrix} 4 & -3 \\ -2 & 7\end{vmatrix} + (-2)\begin{vmatrix} 4 & 9 \\ -2 & -3\end{vmatrix} = 2(54) - 4(22) - 2(6) = 8 .

Same 8, third time.

delete row 1 and column 3the nine bold cells are the minor M₁₃its determinant, signed, is the cofactor C₁₃4 × 43 × 33 × 33 × 33 × 32×22×22×2and the same under each of the others1 then 4 then 12, and 2 numbers in each:24 products, which is 4! again
Fig. 7 

Cofactor expansion is the big formula with the terms grouped instead of listed. It is genuinely recursive: a determinant of size nn calls nn determinants of size n1n-1. Follow the tree to the bottom and you have written out all n!n! terms, one leaf at a time.

Cofactors also give a formula for the inverse, which almost every course leaves out. Collect all n2n^2 cofactors, transpose the result, and you have the adjugate adj(A)\operatorname{adj}(A), whose (i,j)(i, j) entry is CjiC_{ji}. Then

A1=adj(A)detA.A^{-1} = \frac{\operatorname{adj}(A)}{\det A} .

Test it on the tridiagonal KK from Lecture 5. Its determinant is 4, and its nine cofactors turn out to be

adj(K)=[321242123],K1=14[321242123],\operatorname{adj}(K) = \begin{bmatrix} 3 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 3 \end{bmatrix}, \qquad K^{-1} = \tfrac{1}{4}\begin{bmatrix} 3 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 3 \end{bmatrix},

which is the inverse Gauss-Jordan produced back in Lecture 5, arrived at from the opposite direction. The fraction 1/detA1/\det A out front says the same thing again: no inverse when the determinant is zero.

The cross product is a determinant

Here is a formula from physics and graphics that turns out to be this lecture in disguise. For vectors uu and vv in three dimensions, the cross product is

u×v=ijku1u2u3v1v2v3,u \times v = \begin{vmatrix} i & j & k \\ u_1 & u_2 & u_3 \\ v_1 & v_2 & v_3 \end{vmatrix},

with the standard basis vectors written into the top row and cofactor expansion applied along it. The result is a vector, perpendicular to both inputs, and its length is the area of the parallelogram they span. That last fact is not a coincidence. It is this lecture: the area of a parallelogram is a determinant.

u = (2, 1, 0)v = (1, 2, 0)u × v = (0, 0, 3)area 3length 3xyz
Fig. 8 

The two vectors span a parallelogram whose area is the 2×22 \times 2 determinant 2211=32 \cdot 2 - 1 \cdot 1 = 3, and the cross product stands straight out of their plane with length 3. Area and length are the same number because both are determinants of the same pair of vectors.

The right-hand rule, that awkward business with your fingers, is the sign of the determinant. Swap uu and vv and you swap two rows, so v×u=(u×v)v \times u = -(u \times v) and the arrow points the other way.

Cramer’s rule, and its price

Determinants also solve Ax=bAx = b outright. The idea is one trick. Take the identity matrix, replace its first column with the unknown xx, and call the result X1X_1. That matrix is triangular with x1x_1 on the diagonal, so detX1=x1\det X_1 = x_1. Now multiply by AA:

AX1=A[x100x210x301]=[b1a12a13b2a22a23b3a32a33]=B1.A X_1 = A\begin{bmatrix} x_1 & 0 & 0 \\ x_2 & 1 & 0 \\ x_3 & 0 & 1 \end{bmatrix} = \begin{bmatrix} b_1 & a_{12} & a_{13} \\ b_2 & a_{22} & a_{23} \\ b_3 & a_{32} & a_{33} \end{bmatrix} = B_1 .

The first column became AxAx, which is bb. The other columns are copies of AA. Take determinants of both sides and use the product rule:

(detA)(x1)=detB1,x1=detB1detA.(\det A)(x_1) = \det B_1 , \qquad x_1 = \frac{\det B_1}{\det A} .

Repeat with the unknown placed in column ii and you get Cramer’s rule: xi=detBi/detAx_i = \det B_i / \det A, where BiB_i is AA with column ii replaced by bb. On the running example with b=(2,8,10)b = (2, 8, 10), the four determinants are detA=8\det A = 8 and detB1=8\det B_1 = -8, detB2=16\det B_2 = 16, detB3=16\det B_3 = 16, so

x=(88, 168, 168)=(1,2,2),x = \left(\tfrac{-8}{8},\ \tfrac{16}{8},\ \tfrac{16}{8}\right) = (-1, 2, 2),

which is the answer back substitution gave in Lecture 4.

Now the price. Cramer’s rule needs n+1n+1 determinants of size nn. Each one is an elimination, so the total is about n+1n+1 times the cost of just solving the system, and that is the charitable accounting. There is a second problem that is worse and less often mentioned.

python
import numpy as np

def cramer(A, b):
    d = np.linalg.det(A)
    x = []
    for i in range(len(b)):
        B = A.copy()
        B[:, i] = b            # column i swapped for b
        x.append(np.linalg.det(B) / d)
    return np.array(x)

A = np.array([[2., 4., -2.], [4., 9., -3.], [-2., -3., 7.]])
b = np.array([2., 8., 10.])
print(cramer(A, b))            # [-1.  2.  2.]
print(np.linalg.solve(A, b))   # [-1.  2.  2.]   they agree

u, v = np.array([1., 2., 3.]), np.array([4., 5., 6.])
i, j = np.array([1., 0., 0.]), np.array([0., 1., 0.])
print(np.cross(u, v))          # [-3.  6. -3.]
print(np.cross(i, j))          # [0. 0. 1.]     i cross j is k

rng = np.random.default_rng(1)
big = rng.standard_normal((200, 200)) + 200 * np.eye(200)
print(np.linalg.det(big))      # inf, with an overflow warning: |det| is ~1e460

At size 200 the determinant of the matrix above is around 1046010^{460}, and float64 stops at about 1030810^{308}. So detA\det A comes back as infinity, every detBi\det B_i comes back as infinity, and Cramer’s rule returns a vector of nan. Timed on the same matrix, it spends about a hundred times longer than solve to arrive at that answer. The elimination path never forms a determinant at all, so it never notices.

The receipt a flow model keeps

A normalizing flow is a stack of invertible maps. It starts from a simple distribution, pushes it through the stack, and lands on the shape of your data. To train it you need the density it assigns at the far end, and a density is an amount of probability per unit volume. So every layer has to declare how much volume it stretched or squeezed on the way through, and that declaration is the determinant of its Jacobian.

Watch two layers do it with real numbers. The first has Jacobian J1J_1 with rows (1.5,0.5)(1.5, 0.5) and (0,1)(0, 1), so detJ1=1.5\det J_1 = 1.5. The second has rows (0.8,0)(0.8, 0) and (0.4,0.5)(0.4, 0.5), so detJ2=0.4\det J_2 = 0.4.

layer 1det J₁ = 1.5layer 2det J₂ = 0.4area 1area 1.5area 0.6a patch of data spacelog 1.5 + log 0.4 = 0.405 − 0.916 = −0.511one number per layer, added up: the receipt the model is trained on
Fig. 9 

A patch of data space on its way through two layers. The seven dots are the same seven samples throughout, carried along by the maps. The patch leaves with 0.60.6 of the area it started with, so the samples inside it end up packed 1/0.61/0.6 times more tightly, and that packing is the density the model reports.

The areas multiply, 1.5×0.4=0.61.5 \times 0.4 = 0.6, because determinants multiply. Taking logs turns that product into a sum, which is why a flow reports logdetJ\log|\det J| per layer and adds:

logdetJ  =  logdetJ.\log|\det J| \;=\; \sum_{\ell} \log|\det J_\ell| .

Now you can see the shape of the whole field. A general n×nn \times n Jacobian costs n3/3n^3/3 just to get one determinant, per layer, per training step, which no one can afford. So flow architectures are designed backwards from this chapter: build layers whose Jacobian is triangular, where P7 says the determinant is the product of the diagonal and the whole receipt is a sum of nn logarithms. Coupling layers, autoregressive flows, and the triangular tricks behind them all exist to keep that one number cheap.

Where this is going

One number, and it has told you whether a matrix is invertible, how much it scales volume, whether it preserves handedness, and what its inverse is. The next lecture puts it to the use it was really built for.

Ask which directions a matrix leaves pointing the same way. If Ax=λxAx = \lambda x for some nonzero xx, then (AλI)x=0(A - \lambda I)x = 0, so the matrix AλIA - \lambda I has a nonzero null space and must be singular. The test for singular is a determinant:

det(AλI)=0.\det(A - \lambda I) = 0 .

That is a polynomial in λ\lambda, its roots are the eigenvalues, and the whole of Lecture 15 follows from it. There is a second hint waiting there too. The big formula’s diagonal term makes the product of the eigenvalues come out equal to detA\det A, so the volume factor is exactly how much all the special directions stretch, multiplied together.