21.2 Matrices as Linear Maps

In Section 21.1 we read a matrix--vector product Ax\mathbf{A}\mathbf{x} one row at a time: entry ii is the dot product of row ii with x\mathbf{x}, a single hyperplane test. That row view tells us what a matrix computes for one input vector, but it hides what the matrix does to the entire input space at once. In particular, it does not tell us whether the map preserves information or throws it away, and whether its effect can ever be undone.

This question comes up as soon as a neural network layer is narrower than its input. A fully connected layer mapping the 784 pixels of a Fashion-MNIST image to 256 hidden features is a 256×784256 \times 784 matrix. Because its output holds fewer numbers than its input, it must collapse space: by a count we will make precise shortly, at least 784−256=528784 - 256 = 528 independent input directions are sent to zero, so distinct images can produce identical features before any nonlinearity even sees them.

Even a square matrix can lose information. Consider the running matrix of this chapter, A=(12−13)\mathbf{A} = \left(\begin{smallmatrix}1 & 2\\ -1 & 3\end{smallmatrix}\right). It sends (2,−1)(2, -1) to (0,−5)(0, -5), and there is another matrix that sends (0,−5)(0, -5) right back to (2,−1)(2, -1). In fact, that second matrix undoes A\mathbf{A} on every input, so A\mathbf{A} loses nothing. Contrast this with B=(2142)\mathbf{B} = \left(\begin{smallmatrix}2 & 1\\ 4 & 2\end{smallmatrix}\right), which sends both (1,1)(1, 1) and (0,3)(0, 3) to (3,6)(3, 6). Given only the output (3,6)(3, 6), we have no way to tell which input produced it, so no matrix can reverse B\mathbf{B}.

Whether a linear map can be undone determines whether a layer discards information, whether a linear system has a unique solution, and how a probability density rescales under a change of variables (Section 24.2.3.1). To answer this question cleanly, we shift from rows to columns. Column jj of a matrix is simply where it sends the jj-th coordinate axis, and those images alone fix the entire map. Counting how many columns are linearly independent tells us how many input dimensions survive the map, while measuring the signed volume of the transformed unit cube gives a single number that detects whether any dimension was lost. We develop both ideas first in two dimensions, where every statement is a picture, and then extend them to nn dimensions.

Three results organize the section: the balance between surviving and collapsed dimensions, the exact conditions under which a square matrix has an inverse, and the rule for how volume scaling behaves when two maps are composed. The general nn-dimensional construction of the determinant (Section 21.2.3.2) is the most technical part and can be skimmed on a first reading.

import numpy as np

21.2.1 Linear Maps#

21.2.1.1 Columns as Images of the Axes#

A matrix acts on infinitely many input vectors, yet it is stored as a finite table of numbers. How can just four numbers fix the output for every vector in the plane? Take a 2×22 \times 2 matrix A\mathbf{A} with entries p,q,r,sp, q, r, s and apply it to x=(x,y)\mathbf{x} = (x, y). Collecting the terms that multiply xx and those that multiply yy gives

Ax=[pqrs][xy]=[px+qyrx+sy]=x[pr]+y[qs]=x Ae1+y Ae2.\mathbf{A}\mathbf{x} = \begin{bmatrix}p & q \\ r & s\end{bmatrix}\begin{bmatrix}x \\ y\end{bmatrix} = \begin{bmatrix}px+qy\\ rx+sy\end{bmatrix} = x\begin{bmatrix}p \\ r\end{bmatrix} + y\begin{bmatrix}q \\s\end{bmatrix} = x\,\mathbf{A}\mathbf{e}_1 + y\,\mathbf{A}\mathbf{e}_2.

Thus Ax\mathbf{A}\mathbf{x} is simply a weighted sum of the two columns of A\mathbf{A}, using the coordinates of x\mathbf{x} as weights. Because Ae1=(p,r)\mathbf{A}\mathbf{e}_1 = (p, r) and Ae2=(q,s)\mathbf{A}\mathbf{e}_2 = (q, s), the columns are the images of the standard basis vectors e1=(1,0)\mathbf{e}_1 = (1, 0) and e2=(0,1)\mathbf{e}_2 = (0, 1). Once we know where those two axes land, the image of every other vector in the plane is completely determined.

For our running matrix (p=1p = 1, q=2q = 2, r=−1r = -1, s=3s = 3), the two axes go to Ae1=(1,−1)\mathbf{A}\mathbf{e}_1 = (1, -1) and Ae2=(2,3)\mathbf{A}\mathbf{e}_2 = (2, 3). Since the input v=(2,−1)\mathbf{v} = (2, -1) is 2e1−e22\mathbf{e}_1 - \mathbf{e}_2, its image is the exact same combination of the columns:

Av=2 (1,−1)−(2,3)=(0,−5).\mathbf{A}\mathbf{v} = 2\,(1, -1) - (2, 3) = (0, -5).

Checking by rows confirms the result: (1,2)⋅(2,−1)=0(1, 2)\cdot(2, -1) = 0 and (−1,3)⋅(2,−1)=−5(-1, 3)\cdot(2, -1) = -5. Both views compute the same product, but the column view lets us see what A\mathbf{A} does to the entire plane at once. Figure 21.2.1 illustrates this geometry: the unit square spanned by e1\mathbf{e}_1 and e2\mathbf{e}_2 is carried to the parallelogram spanned by the two columns, and the grid point v\mathbf{v} lands on the corresponding point Av\mathbf{A}\mathbf{v} of the transformed grid.

Figure 21.2.1:

The running matrix A=(12−13)\mathbf{A} = \left(\begin{smallmatrix}1 & 2\\ -1 & 3\end{smallmatrix}\right) acting on the plane. (a) The input grid, shaded unit square, basis vectors, and input v=(2,−1)\mathbf{v} = (2, -1). (b) Its image: e1\mathbf{e}_1 goes to (1,−1)(1, -1), e2\mathbf{e}_2 to (2,3)(2, 3), and v\mathbf{v} to (0,−5)(0, -5). Lines remain lines, the origin stays fixed, and equally spaced points stay equally spaced. The shaded square maps to the shaded parallelogram, whose area leads to the determinant. Panel (b) is drawn at one-third the scale of (a).

The same column picture holds in any dimension. An m×nm \times n matrix maps vectors in Rn\mathbb{R}^n to vectors in Rm\mathbb{R}^m, and it is linear:

A(αx+βy)=α Ax+β Ayfor all x,y∈Rn and α,β∈R.\mathbf{A}(\alpha\mathbf{x} + \beta\mathbf{y}) = \alpha\,\mathbf{A}\mathbf{x} + \beta\,\mathbf{A}\mathbf{y} \quad \textrm{for all } \mathbf{x}, \mathbf{y} \in \mathbb{R}^n \textrm{ and } \alpha, \beta \in \mathbb{R}.

In words, the image of a weighted sum is the same weighted sum of the images. Writing any input as x=∑jxjej\mathbf{x} = \sum_j x_j \mathbf{e}_j gives Ax=∑jxj Aej\mathbf{A}\mathbf{x} = \sum_j x_j\,\mathbf{A}\mathbf{e}_j, where multiplying by ej\mathbf{e}_j picks out column jj. Conversely, every map f:Rn→Rmf : \mathbb{R}^n \to \mathbb{R}^m that satisfies this linearity rule can be written as a matrix whose jj-th column is f(ej)f(\mathbf{e}_j), because f(x)=f(∑jxjej)=∑jxjf(ej)f(\mathbf{x}) = f(\sum_j x_j\mathbf{e}_j) = \sum_j x_j f(\mathbf{e}_j). Linear maps from Rn\mathbb{R}^n to Rm\mathbb{R}^m and m×nm \times n matrices are therefore two ways of describing the same object.

Linearity is also what keeps the grid in Figure 21.2.1 looking like a grid. Every line p+tu\mathbf{p} + t\mathbf{u} maps to Ap+t Au\mathbf{A}\mathbf{p} + t\,\mathbf{A}\mathbf{u}, which is again a line (or a single point if Au=0\mathbf{A}\mathbf{u} = \mathbf{0}), and the origin never moves: A0=0\mathbf{A}\mathbf{0} = \mathbf{0}.

Nothing here requires the matrix to be square. A 2×32 \times 3 matrix maps R3\mathbb{R}^3 into the span of its three columns in R2\mathbb{R}^2, filling the whole output plane as long as at least two columns are linearly independent. Going the other way, a 3×23 \times 2 matrix maps the plane into R3\mathbb{R}^3, where its outputs form a plane through the origin, a line, or the origin alone, depending on its two columns. Every fully connected layer in a neural network is a rectangular map of this kind, followed by a bias shift and a nonlinearity.

To build visual intuition, Figure 21.2.2 displays six 2×22 \times 2 matrices through their effect on the unit square. A 90∘90^\circ counter-clockwise rotation sends e1\mathbf{e}_1 to e2\mathbf{e}_2 and e2\mathbf{e}_2 to −e1-\mathbf{e}_1, so its columns are (0,1)(0, 1) and (−1,0)(-1, 0). A horizontal shear leaves e1\mathbf{e}_1 untouched and tilts e2\mathbf{e}_2 to (1,1)(1, 1), sliding every horizontal line sideways in proportion to its height. The last two panels are qualitatively different: they lose a dimension, flattening the entire square, and with it the entire plane, onto a single line.

One familiar operation is noticeably absent from this gallery: a translation x↦x+c\mathbf{x} \mapsto \mathbf{x} + \mathbf{c} with c≠0\mathbf{c} \neq \mathbf{0}. Because it moves the origin, it is not linear. An affine layer Wx+b\mathbf{W}\mathbf{x} + \mathbf{b} in a neural network is therefore a linear map followed by a translation.

21.2.1.2 Composition#

Two linear layers placed back to back, with no nonlinearity between them, collapse into a single linear map. Which matrix represents that combined map? Let us test this on two concrete maps from Figure 21.2.2: the 90∘90^\circ rotation R90\mathbf{R}_{90} and the shear T\mathbf{T} (named for how it tilts the vertical axis),

R90=[0−110],T=[1101].\mathbf{R}_{90} = \begin{bmatrix}0 & -1\\ 1 & 0\end{bmatrix}, \qquad \mathbf{T} = \begin{bmatrix}1 & 1\\ 0 & 1\end{bmatrix}.

Both matrices will reappear throughout the chapter. Let us track where the standard basis vectors go under each ordering. If we shear first, e1\mathbf{e}_1 stays at (1,0)(1, 0) and the rotation sends it to (0,1)(0, 1); meanwhile e2\mathbf{e}_2 shears to (1,1)(1, 1) and rotates to (−1,1)(-1, 1). Thus "shear, then rotate" has columns (0,1)(0, 1) and (−1,1)(-1, 1). In the opposite order, rotating sends e1\mathbf{e}_1 to (0,1)(0, 1), which the shear moves to (1,1)(1, 1), and sends e2\mathbf{e}_2 to (−1,0)(-1, 0), which the shear leaves unchanged. The two composites are therefore

shear, then rotate: [0−111],rotate, then shear: [1−110].\textrm{shear, then rotate: }\begin{bmatrix}0 & -1\\ 1 & 1\end{bmatrix}, \qquad \textrm{rotate, then shear: }\begin{bmatrix}1 & -1\\ 1 & 0\end{bmatrix}.

They are not the same map, as Figure 21.2.3 makes clear.

Figure 21.2.3:

The order of composition matters. (a) Applying the shear T\mathbf{T} (dotted outline) followed by the rotation R90\mathbf{R}_{90} produces R90T\mathbf{R}_{90}\mathbf{T}. (b) Applying the rotation (dotted outline) followed by the shear produces TR90\mathbf{T}\mathbf{R}_{90}. The labels show the final images of e1\mathbf{e}_1 (blue) and e2\mathbf{e}_2 (orange). Matrix products are always read from right to left.

Matrix multiplication is the algebraic rule that computes such composites. For any two matrices A\mathbf{A} and B\mathbf{B} whose dimensions match, apply B\mathbf{B} to v\mathbf{v}, then A\mathbf{A} to the result, and inspect entry ii:

(A(Bv))i=∑jaij(Bv)j=∑j∑kaijbjkvk=∑k(∑jaijbjk)vk=((AB)v)i.(21.2.1)\bigl(\mathbf{A}(\mathbf{B}\mathbf{v})\bigr)_i = \sum_j a_{ij} (\mathbf{B}\mathbf{v})_j = \sum_j \sum_k a_{ij} b_{jk} v_k = \sum_k \Bigl(\sum_j a_{ij} b_{jk}\Bigr) v_k = \bigl((\mathbf{A}\mathbf{B})\mathbf{v}\bigr)_i. \tag{21.2.1}

Applying the two maps in sequence is identical to applying the single matrix AB\mathbf{A}\mathbf{B}, whose (i,k)(i, k) entry is the dot product of row ii of A\mathbf{A} with column kk of B\mathbf{B}. Notice the order: the product AB\mathbf{A}\mathbf{B} means "apply B\mathbf{B} first, then A\mathbf{A}," read from right to left just like function composition f(g(x))f(g(x)). Setting v=ej\mathbf{v} = \mathbf{e}_j in (21.2.1) also gives a useful column rule: column jj of AB\mathbf{A}\mathbf{B} is Abj\mathbf{A}\mathbf{b}_j, the image under A\mathbf{A} of column jj of B\mathbf{B}. We will lean on this fact when we study the determinant.

Seeing multiplication as composition explains its seemingly odd definition. The row-times-column formula is not an arbitrary convention; it is simply what composing two linear maps produces. It also makes the algebraic properties immediate. Matrix multiplication is associative, (AB)C=A(BC)(\mathbf{A}\mathbf{B})\mathbf{C} = \mathbf{A}(\mathbf{B}\mathbf{C}), because function composition is associative: both sides apply C\mathbf{C}, then B\mathbf{B}, then A\mathbf{A}. And it is not commutative in general, because performing two geometric operations in opposite orders usually leads to different results. In NumPy, matrix multiplication uses the @ operator. Let us check that it reproduces both composites of the rotation and the shear (stored as R90 and S below).

R90 = np.array([[0.0, -1.0], [1.0, 0.0]])  # rotation by 90 degrees
S = np.array([[1.0, 1.0], [0.0, 1.0]])     # shear
print(R90 @ S)
print(S @ R90)
[[ 0. -1.]
 [ 1.  1.]]
[[ 1. -1.]
 [ 1.  0.]]

Of course, some pairs of matrices do commute. Two rotations in the plane commute, since rotating by ϕ\phi and then by ψ\psi yields a rotation by ϕ+ψ\phi + \psi in either order. Two diagonal matrices commute as well, since each scales the coordinate axes independently. Exercise 3 characterizes every 2×22 \times 2 matrix that commutes with R90\mathbf{R}_{90}.

21.2.1.3 Orthogonal Matrices#

Some linear maps move space rigidly, leaving every length and every angle untouched. Which matrices have this property? Consider a counter-clockwise rotation by an angle ϕ\phi in the plane. It sends e1\mathbf{e}_1 to (cos⁡ϕ,sin⁡ϕ)(\cos\phi, \sin\phi) and e2\mathbf{e}_2 to (−sin⁡ϕ,cos⁡ϕ)(-\sin\phi, \cos\phi), so its matrix is

Rϕ=[cos⁡ϕ−sin⁡ϕsin⁡ϕcos⁡ϕ].\mathbf{R}_\phi = \begin{bmatrix}\cos\phi & -\sin\phi\\ \sin\phi & \cos\phi\end{bmatrix}.

Its columns have unit length, cos⁡2ϕ+sin⁡2ϕ=1\sqrt{\cos^2\phi + \sin^2\phi} = 1, and zero dot product, −cos⁡ϕsin⁡ϕ+sin⁡ϕcos⁡ϕ=0-\cos\phi\sin\phi + \sin\phi\cos\phi = 0. They are orthonormal, a condition we wrote in Section 21.1 as Rϕ⊤Rϕ=I\mathbf{R}_\phi^\top\mathbf{R}_\phi = \mathbf{I}. Setting ϕ=90∘\phi = 90^\circ recovers R90\mathbf{R}_{90}, which sends (3,2)(3, 2) to (−2,3)(-2, 3); both vectors have length 13\sqrt{13}. The reflection diag⁡(1,−1)\operatorname{diag}(1, -1) across the xx-axis has orthonormal columns as well.

In any dimension, a square matrix Q\mathbf{Q} is called orthogonal when its columns are orthonormal, that is,

Q⊤Q=I.\mathbf{Q}^\top\mathbf{Q} = \mathbf{I}.

Two subtleties in this definition are worth flagging. First, columns that are merely perpendicular are not enough: diag⁡(1,10)\operatorname{diag}(1, 10) has perpendicular columns of lengths 11 and 1010, yet it bends the 90∘90^\circ angle between (1,1)(1, 1) and (1,−1)(1, -1) into arccos⁡(−99/101)≈169∘\arccos(-99/101) \approx 169^\circ (1). Second, the name "orthogonal" is reserved for square matrices. A tall n×kn \times k matrix with k<nk \lt n orthonormal columns still preserves lengths, but it embeds Rk\mathbb{R}^k into a larger space Rn\mathbb{R}^n and therefore has no two-sided inverse (Section 21.2.2.3).

An orthogonal map preserves every dot product:

(Qx)⋅(Qy)=(Qx)⊤(Qy)=x⊤Q⊤Q y=x⊤y=x⋅y.(\mathbf{Q}\mathbf{x})\cdot(\mathbf{Q}\mathbf{y}) = (\mathbf{Q}\mathbf{x})^\top(\mathbf{Q}\mathbf{y}) = \mathbf{x}^\top\mathbf{Q}^\top\mathbf{Q}\,\mathbf{y} = \mathbf{x}^\top\mathbf{y} = \mathbf{x}\cdot\mathbf{y}.

Setting y=x\mathbf{y} = \mathbf{x} gives ∥Qx∥=∥x∥\|\mathbf{Q}\mathbf{x}\| = \|\mathbf{x}\|, so lengths are unchanged; and because angles depend only on dot products and lengths, angles are unchanged as well. If you rotate an entire set of embedding vectors by the same orthogonal matrix, every pairwise cosine similarity stays identical.

The defining equation Q⊤Q=I\mathbf{Q}^\top\mathbf{Q} = \mathbf{I} says that applying Q⊤\mathbf{Q}^\top after Q\mathbf{Q} undoes it. For a square matrix Q\mathbf{Q}, it turns out that Q⊤\mathbf{Q}^\top also undoes Q\mathbf{Q} when applied before it, QQ⊤=I\mathbf{Q}\mathbf{Q}^\top = \mathbf{I}, meaning the rows of Q\mathbf{Q} are orthonormal too and Q−1=Q⊤\mathbf{Q}^{-1} = \mathbf{Q}^\top. This is not obvious from the definition alone; it follows from a general theorem on square matrices that we prove in Section 21.2.2.3.

In two dimensions, rotations and reflections are the only orthogonal matrices. The first column must be a unit vector (cos⁡ϕ,sin⁡ϕ)(\cos\phi, \sin\phi), which leaves only two unit vectors perpendicular to it for the second column: ±(−sin⁡ϕ,cos⁡ϕ)\pm(-\sin\phi, \cos\phi). The plus sign gives the rotation Rϕ\mathbf{R}_\phi. The minus sign gives Rϕdiag⁡(1,−1)\mathbf{R}_\phi\operatorname{diag}(1, -1), a reflection across the xx-axis followed by a rotation, which is itself a reflection across a line through the origin. Later, the sign of the determinant will separate rotations from reflections at a glance (Section 21.2.3.3).

21.2.1.4 Tensors and Einstein Summation#

In a transformer, self-attention compares every query with every key, across every attention head and every sequence in a batch. Labeling the batch by bb, the head by hh, the query position by ii, the key position by tt, and the feature dimension within a head by jj, the attention scores are

sbhit=∑jqbhij kbhtj,s_{bhit} = \sum_j q_{bhij}\, k_{bhtj},

where qbhijq_{bhij} and kbhtjk_{bhtj} are entries of the four-axis query and key tensors (Section 1.1). Each score is a dot product along the feature axis jj, evaluated for every combination of the other four indices. Standard matrix notation has no clean way to write this four-index contraction; calling it "a batched matrix multiplication with a transpose on the last two axes" obscures which axis is actually being summed.

Step back, and notice that every product we have met so far follows the exact same pattern. The dot product, the matrix--vector product, the matrix product, and the trace tr⁡(A)\operatorname{tr}(\mathbf{A}) (the sum of the diagonal entries of a square matrix) all read

v⋅w=∑iviwi,(Av)i=∑jaijvj,(AB)ik=∑jaijbjk,tr⁡(A)=∑iaii.\mathbf{v} \cdot \mathbf{w} = \sum_i v_i w_i, \qquad (\mathbf{A}\mathbf{v})_i = \sum_j a_{ij} v_j, \qquad (\mathbf{A}\mathbf{B})_{ik} = \sum_j a_{ij} b_{jk}, \qquad \operatorname{tr}(\mathbf{A}) = \sum_i a_{ii}.

The trace is new here and will return in Section 21.3 as the sum of a matrix's eigenvalues. Each of these four formulas multiplies entries together and sums over an index that appears twice. Einstein notation turns that pattern into a convention: drop the summation sign and automatically sum over every repeated index. Under this rule, v⋅w=viwi\mathbf{v}\cdot\mathbf{w} = v_i w_i and (AB)ik=aijbjk(\mathbf{A}\mathbf{B})_{ik} = a_{ij}b_{jk}.

The attention scores reveal where the classical convention falls short: the batch and head indices bb and hh appear in both factors, yet we want to keep them rather than sum them out. Numerical libraries solve this in einsum by having you name the kept indices explicitly. You pass a string listing the input indices, an arrow ->, and the output indices; any index omitted from the right-hand side is summed over. Let us express our four basic products this way and check them on our running matrices.

A = np.array([[1.0, 2.0], [-1.0, 3.0]])    # the running matrix
v = np.array([2.0, -1.0])
(np.einsum('i,i->', v, v),        # dot product: v.v
 np.einsum('ij,j->i', A, v),      # matrix-vector product: Av
 np.einsum('ij,jk->ik', R90, S),  # matrix product: R90 S
 np.einsum('ii->', A))            # trace: tr(A)
(np.float64(5.0),
 array([ 0., -5.]),
 array([[ 0., -1.],
        [ 1.,  1.]]),
 np.float64(4.0))

Every output matches our hand calculations from earlier, including tr⁡A=1+3=4\operatorname{tr}\mathbf{A} = 1 + 3 = 4. The attention scores take just one line in the same notation. Below, we compute them with einsum, verify that they agree with a batched matrix product against the transposed keys, and count the total number of multiply--adds.

rng = np.random.default_rng()
queries = rng.standard_normal((2, 3, 4, 8))   # (batch, heads, queries, width)
keys = rng.standard_normal((2, 3, 5, 8))      # (batch, heads, keys, width)
scores = np.einsum('bhij,bhtj->bhit', queries, keys)
(scores.shape, np.allclose(scores, queries @ keys.swapaxes(-1, -2)),
 scores.size * queries.shape[-1])             # multiply-adds
((2, 3, 4, 5), True, 960)

The output has shape (2,3,4,5)(2, 3, 4, 5), giving one 4×54 \times 5 score table per sequence and head. Both expressions agree, and the contraction takes 2⋅3⋅4⋅5⋅8=9602 \cdot 3 \cdot 4 \cdot 5 \cdot 8 = 960 multiply--adds, which is simply the product of the sizes of all five indices.

Beyond code, index notation yields effortless one-line proofs. For any A∈Rm×n\mathbf{A} \in \mathbb{R}^{m \times n} and B∈Rn×m\mathbf{B} \in \mathbb{R}^{n \times m}, both AB\mathbf{A}\mathbf{B} and BA\mathbf{B}\mathbf{A} are square, and their traces satisfy

tr⁡(AB)=aijbji=bjiaij=tr⁡(BA).(21.2.2)\operatorname{tr}(\mathbf{A}\mathbf{B}) = a_{ij} b_{ji} = b_{ji} a_{ij} = \operatorname{tr}(\mathbf{B}\mathbf{A}). \tag{21.2.2}

The middle step merely swaps two scalar numbers while leaving the indices alone. Surprisingly, the trace of a product does not depend on the order of the two factors, even when AB≠BA\mathbf{A}\mathbf{B} \neq \mathbf{B}\mathbf{A} and even when the two products do not have the same dimensions. One immediate consequence will matter when we study eigenvalues: if V\mathbf{V} has an inverse V−1\mathbf{V}^{-1} (Section 21.2.2.3), then tr⁡(VAV−1)=tr⁡(AV−1V)=tr⁡(A)\operatorname{tr}(\mathbf{V}\mathbf{A}\mathbf{V}^{-1}) = \operatorname{tr}(\mathbf{A}\mathbf{V}^{-1}\mathbf{V}) = \operatorname{tr}(\mathbf{A}). Because VAV−1\mathbf{V}\mathbf{A}\mathbf{V}^{-1} represents the same linear map A\mathbf{A} written in a different coordinate system, the trace is an intrinsic property of the map rather than an artifact of the coordinates we chose. The determinant will turn out to share this invariance (Section 21.2.3.3).

One practical warning: when an einsum expression combines three or more tensors, the string specifies the mathematical result but not the order in which pairwise contractions are carried out, and that order can make a huge difference in speed. For n×nn \times n matrices, computing (AB)v(\mathbf{A}\mathbf{B})\mathbf{v} takes roughly n3n^3 multiply--adds, whereas computing A(Bv)\mathbf{A}(\mathbf{B}\mathbf{v}) takes only 2n22n^2.

21.2.2 Rank and Invertibility#

21.2.2.1 Column Space and Null Space#

Which outputs can a matrix actually produce, and which inputs does it erase? To see both at once, examine our singular example

B=[2142].\mathbf{B} = \begin{bmatrix} 2 & 1 \\ 4 & 2 \end{bmatrix}.

Its columns are b1=(2,4)\mathbf{b}_1 = (2, 4) and b2=(1,2)\mathbf{b}_2 = (1, 2), so one is simply twice the other: b1=2b2\mathbf{b}_1 = 2\mathbf{b}_2. Because every output of B\mathbf{B} is a weighted sum of its columns, every output collapses to a scalar multiple of b2\mathbf{b}_2:

a1b1+a2b2=(2a1+a2) b2.a_1\mathbf{b}_1 + a_2\mathbf{b}_2 = (2a_1 + a_2)\,\mathbf{b}_2.

Thus B\mathbf{B} sends the entire two-dimensional plane onto the single line y=2xy = 2x through (1,2)(1, 2). Inevitably, distinct inputs collide on that line: both (1,1)(1, 1) and (0,3)(0, 3) land on (3,6)(3, 6). By linearity, their difference (1,−2)(1, -2) must map to the difference of their outputs, B(1,−2)=0\mathbf{B}(1, -2) = \mathbf{0}. The row view gives a second way to see why: both rows of B\mathbf{B}, (2,1)(2, 1) and (4,2)(4, 2), are perpendicular to (1,−2)(1, -2), so both hyperplane tests return zero. Figure 21.2.4 shows both lines side by side.

Figure 21.2.4:

The matrix B=(2142)\mathbf{B} = \left(\begin{smallmatrix}2 & 1\\ 4 & 2\end{smallmatrix}\right) collapsing the plane. (a) In the input plane, the dashed null-space line through (1,−2)(1, -2) is perpendicular to the row direction (2,1)(2, 1); three inputs are marked: x1=(1,1)\mathbf{x}_1 = (1, 1), x2=(0,3)\mathbf{x}_2 = (0, 3), and x3=(1,−2)\mathbf{x}_3 = (1, -2) on the null-space line. (b) In the output plane (same scale), every output lands on the column space, the line y=2xy = 2x spanned by b1\mathbf{b}_1 and b2\mathbf{b}_2; both x1\mathbf{x}_1 and x2\mathbf{x}_2 map to (3,6)(3, 6), while x3\mathbf{x}_3 collapses to the origin. Because distinct inputs share the same image, no inverse can exist.

This example illustrates two fundamental subspaces attached to every m×nm \times n matrix A\mathbf{A}. The column space, written col⁡A\operatorname{col}\mathbf{A}, is the span of the columns of A\mathbf{A}. Since Ax\mathbf{A}\mathbf{x} is a weighted combination of the columns with weights x1,…,xnx_1, \ldots, x_n, the column space is precisely the set of all reachable outputs. The null space, also called the kernel and written ker⁡A\ker\mathbf{A}, is the set of all inputs that A\mathbf{A} sends to zero:

ker⁡A={x∈Rn:Ax=0}.\ker\mathbf{A} = \{\mathbf{x} \in \mathbb{R}^n : \mathbf{A}\mathbf{x} = \mathbf{0}\}.

It is a subspace of Rn\mathbb{R}^n: if Ax=Ay=0\mathbf{A}\mathbf{x} = \mathbf{A}\mathbf{y} = \mathbf{0}, then A(αx+βy)=αAx+βAy=0\mathbf{A}(\alpha\mathbf{x} + \beta\mathbf{y}) = \alpha\mathbf{A}\mathbf{x} + \beta\mathbf{A}\mathbf{y} = \mathbf{0}. For B\mathbf{B}, the column space is the line y=2xy = 2x in the output plane, and the null space is the line through (1,−2)(1, -2) in the input plane. (That both live in R2\mathbb{R}^2 is just an accident of B\mathbf{B} being square; in general, ker⁡A⊆Rn\ker\mathbf{A} \subseteq \mathbb{R}^n and col⁡A⊆Rm\operatorname{col}\mathbf{A} \subseteq \mathbb{R}^m.)

Three general facts carry straight over from this example:

  1. The null space consists of all inputs perpendicular to every row. In the row view, (Ax)i(\mathbf{A}\mathbf{x})_i is the dot product of row ii with x\mathbf{x}, so all entries of Ax\mathbf{A}\mathbf{x} vanish if and only if x\mathbf{x} is orthogonal to every row.
  2. The columns are linearly dependent if and only if the null space contains a nonzero vector. A nontrivial dependence ∑jxjaj=0\sum_j x_j\mathbf{a}_j = \mathbf{0} among the columns aj\mathbf{a}_j simply says Ax=0\mathbf{A}\mathbf{x} = \mathbf{0} for a nonzero vector x\mathbf{x}, and reading the equation backwards gives the converse. For B\mathbf{B}, the relation b1−2b2=0\mathbf{b}_1 - 2\mathbf{b}_2 = \mathbf{0} yields the null vector (1,−2)(1, -2).
  3. Two inputs produce the same output if and only if they differ by a null vector. Indeed, Ax=Ay\mathbf{A}\mathbf{x} = \mathbf{A}\mathbf{y} is equivalent to A(x−y)=0\mathbf{A}(\mathbf{x} - \mathbf{y}) = \mathbf{0}. The set of all inputs that B\mathbf{B} maps to (3,6)(3, 6) is the shifted line (1,1)+t(1,−2)(1, 1) + t(1, -2), which passes through (0,3)(0, 3) at t=−1t = -1. Whenever ker⁡A\ker\mathbf{A} contains a nonzero vector, distinct inputs collide and no inverse can exist.

21.2.2.2 Rank#

How many input dimensions survive a linear map? The rank of a matrix is the dimension of its column space, or equivalently the maximum number of linearly independent columns:

rank⁡A=dim⁡col⁡A.\operatorname{rank}\mathbf{A} = \dim\operatorname{col}\mathbf{A}.

Our matrix B\mathbf{B} has rank 11: its two columns are dependent, and neither is zero. For a richer example, consider the 4×54 \times 5 matrix

C=[130−10−1011−10310−123−1−21],\mathbf{C} = \begin{bmatrix} 1& 3 & 0 & -1 & 0 \\ -1 & 0 & 1 & 1 & -1 \\ 0 & 3 & 1 & 0 & -1 \\ 2 & 3 & -1 & -2 & 1 \end{bmatrix},

which has rank 22: its first two columns are linearly independent, yet every one of the (53)=10\binom{5}{3} = 10 triples of columns is linearly dependent.

Remarkably, the number of dimensions that survive the map and the number of dimensions crushed to zero always add up to the dimension of the input space.

Proposition (rank--nullity). For an m×nm \times n matrix A\mathbf{A},

rank⁡A+dim⁡ker⁡A=n.(21.2.3)\operatorname{rank}\mathbf{A} + \dim\ker\mathbf{A} = n. \tag{21.2.3}

Proof. Pick a basis w1,…,wk\mathbf{w}_1, \ldots, \mathbf{w}_k of ker⁡A\ker\mathbf{A} and extend it to a basis w1,…,wk,u1,…,un−k\mathbf{w}_1, \ldots, \mathbf{w}_k, \mathbf{u}_1, \ldots, \mathbf{u}_{n-k} of Rn\mathbb{R}^n. (That any linearly independent list can be extended to a basis, and that all bases of a subspace have the same size, are standard facts we use without proof.) The images Au1,…,Aun−k\mathbf{A}\mathbf{u}_1, \ldots, \mathbf{A}\mathbf{u}_{n-k} span col⁡A\operatorname{col}\mathbf{A}, because any input x∈Rn\mathbf{x} \in \mathbb{R}^n is a combination of the full basis and the wj\mathbf{w}_j vanish under A\mathbf{A}. They are also linearly independent: if ∑iciAui=0\sum_i c_i \mathbf{A}\mathbf{u}_i = \mathbf{0}, then ∑iciui\sum_i c_i \mathbf{u}_i lies in ker⁡A\ker\mathbf{A} and can therefore be written as a combination of w1,…,wk\mathbf{w}_1, \ldots, \mathbf{w}_k. Within a basis, that is impossible unless every ci=0c_i = 0. Hence col⁡A\operatorname{col}\mathbf{A} has dimension n−kn - k. ■\blacksquare

Figure 21.2.5 shows the basis that the proof builds. Each of its nn vectors either vanishes under A\mathbf{A} or contributes one dimension to the column space, and no vector does both.

Figure 21.2.5:

The basis in the proof of rank--nullity. The kk vectors w1,…,wk\mathbf{w}_1, \ldots, \mathbf{w}_k span ker⁡A\ker\mathbf{A} and are sent to 0\mathbf{0}. The n−kn-k vectors u1,…,un−k\mathbf{u}_1, \ldots, \mathbf{u}_{n-k} complete them to a basis of Rn\mathbb{R}^n, and their images form a basis of col⁡A\operatorname{col}\mathbf{A}.

Let us check this conservation of dimensions on our examples. For B\mathbf{B} we get 1+1=21 + 1 = 2. For the 256×784256 \times 784 Fashion-MNIST layer from the opening, the rank cannot exceed the 256256 output coordinates, so the null space must have dimension at least 784−256=528784 - 256 = 528. For C\mathbf{C}, the null space must have dimension 5−2=35 - 2 = 3, meaning any three linearly independent null vectors form a basis of ker⁡C\ker\mathbf{C}. Below, we verify that (3,−1,3,0,0)(3, -1, 3, 0, 0), (1,0,0,1,0)(1, 0, 0, 1, 0), and (0,0,1,0,1)(0, 0, 1, 0, 1) all map to zero under C\mathbf{C} and check the rank of the matrix Z holding them as columns.

B = np.array([[2.0, 1.0], [4.0, 2.0]])
C = np.array([[1, 3, 0, -1, 0], [-1, 0, 1, 1, -1],
              [0, 3, 1, 0, -1], [2, 3, -1, -2, 1]], dtype=float)
Z = np.array([[3, -1, 3, 0, 0], [1, 0, 0, 1, 0],
              [0, 0, 1, 0, 1]], dtype=float).T   # candidate null vectors
rank_C, rank_Z = np.linalg.matrix_rank(C), np.linalg.matrix_rank(Z)
np.linalg.matrix_rank(B), rank_C, np.abs(C @ Z).max(), rank_Z, rank_C + rank_Z
(np.int64(1), np.int64(2), np.float64(0.0), np.int64(3), np.int64(5))

The ranks of B\mathbf{B} and C\mathbf{C} come out to 11 and 22, the maximum entry of ∣CZ∣|\mathbf{C}\mathbf{Z}| is zero, and the three columns of Z have rank 33, confirming 2+3=52 + 3 = 5.

What if we read a matrix by rows instead of columns? Its row rank, the maximum number of linearly independent rows, counts how many independent hyperplane tests the matrix performs. In C\mathbf{C}, row 3 is row 1 plus row 2 and row 4 is row 1 minus row 2, so the row rank is 22, matching the column rank. That agreement is universal.

Proposition (row rank equals column rank). For every matrix A\mathbf{A}, the largest number of linearly independent rows equals the largest number of linearly independent columns.

Proof. Let r=rank⁡Ar = \operatorname{rank}\mathbf{A}, and place a basis of col⁡A\operatorname{col}\mathbf{A} into the columns of an m×rm \times r matrix G\mathbf{G}. Since every column of A\mathbf{A} is a linear combination of the columns of G\mathbf{G}, storing the coefficients for column jj of A\mathbf{A} in column jj of an r×nr \times n matrix H\mathbf{H} gives the factorization

A=GH.(21.2.4)\mathbf{A} = \mathbf{G}\mathbf{H}. \tag{21.2.4}

Now read the same product by rows. Row ii of A\mathbf{A} is ∑kgik (row k of H)\sum_k g_{ik}\,(\textrm{row } k \textrm{ of } \mathbf{H}), so every row of A\mathbf{A} lies in the span of the rr rows of H\mathbf{H}. Thus the row rank of A\mathbf{A} is at most rr. Repeating the argument for A⊤\mathbf{A}^\top, whose columns are the rows of A\mathbf{A}, shows that the column rank is at most the row rank, so the two must be equal. ■\blacksquare

The factorization A=GH\mathbf{A} = \mathbf{G}\mathbf{H} is more than a proof device. It reveals that any rank-rr matrix passes its input through a bottleneck of width rr: H\mathbf{H} compresses x∈Rn\mathbf{x} \in \mathbb{R}^n to rr numbers, and G\mathbf{G} expands those rr numbers back to Rm\mathbb{R}^m. When rr is much smaller than mm and nn, storing G\mathbf{G} and H\mathbf{H} requires only r(m+n)r(m + n) parameters instead of mnmn, which is the core idea behind the low-rank updates of Section 21.5.4.1.

In practice, finding rank by testing subsets of columns would take exponentially long. By hand one uses Gaussian elimination (which this chapter does not cover). Numerical libraries like np.linalg.matrix_rank instead count how many singular values (Section 21.5) exceed a small tolerance. A tolerance is unavoidable because rank is not a continuous function of the matrix entries: a tiny perturbation can jump the rank from deficient to full (Section 21.2.3.6).

21.2.2.3 Inverses#

Given an output Ax\mathbf{A}\mathbf{x}, when can we reliably recover the input x\mathbf{x}? An inverse of a square matrix A\mathbf{A} is a matrix A−1\mathbf{A}^{-1} that undoes A\mathbf{A} from both sides:

A−1A=AA−1=I,\mathbf{A}^{-1}\mathbf{A} = \mathbf{A}\mathbf{A}^{-1} = \mathbf{I},

so that x=A−1(Ax)\mathbf{x} = \mathbf{A}^{-1}(\mathbf{A}\mathbf{x}) for every input x\mathbf{x}. For a 2×22 \times 2 matrix with entries p,q,r,sp, q, r, s satisfying ps−qr≠0ps - qr \neq 0, there is an explicit formula:

A−1=1ps−qr[s−q−rp].(21.2.5)\mathbf{A}^{-1} = \frac{1}{ps - qr}\begin{bmatrix} s & -q \\ -r & p \end{bmatrix}. \tag{21.2.5}

A quick multiplication confirms it: multiplying (s−q−rp)\left(\begin{smallmatrix}s & -q\\ -r & p\end{smallmatrix}\right) by A\mathbf{A} in either order yields (ps−qr) I(ps - qr)\,\mathbf{I}, and dividing by ps−qrps - qr leaves I\mathbf{I}. The condition ps−qr≠0ps - qr \neq 0 cannot be dropped. If ps−qr=0ps - qr = 0, that product is the zero matrix; multiplying both sides by a hypothetical inverse A−1\mathbf{A}^{-1} would force (s−q−rp)=0\left(\begin{smallmatrix}s & -q\\ -r & p\end{smallmatrix}\right) = \mathbf{0}, and hence A=0\mathbf{A} = \mathbf{0}, which plainly has no inverse. We will meet the quantity ps−qrps - qr again as a signed area in Section 21.2.3.1. For our running matrix, ps−qr=3+2=5ps - qr = 3 + 2 = 5, so

A−1=15[3−211],A−1(0,−5)=15 (10,−5)=(2,−1).\mathbf{A}^{-1} = \frac{1}{5}\begin{bmatrix} 3 & -2 \\ 1 & 1 \end{bmatrix}, \qquad \mathbf{A}^{-1}(0, -5) = \tfrac15\,(10, -5) = (2, -1).

Sure enough, A−1\mathbf{A}^{-1} reverses the worked example of Section 21.2.1.1.

Whenever an inverse exists, it is unique. Even better, any left inverse and any right inverse of the same matrix must coincide: if LA=I\mathbf{L}\mathbf{A} = \mathbf{I} and AX=I\mathbf{A}\mathbf{X} = \mathbf{I}, then by associativity,

L=L(AX)=(LA)X=X.\mathbf{L} = \mathbf{L}(\mathbf{A}\mathbf{X}) = (\mathbf{L}\mathbf{A})\mathbf{X} = \mathbf{X}.

When does an inverse exist in general? For a square matrix, the answer requires only the null space and rank--nullity, and the rest of this chapter relies on it more than on any other result in this section.

Proposition (invertible matrices). For an n×nn \times n matrix A\mathbf{A}, the following are equivalent: (i) A\mathbf{A} is invertible; (ii) the columns of A\mathbf{A} are linearly independent; (iii) ker⁡A={0}\ker\mathbf{A} = \{\mathbf{0}\}; (iv) rank⁡A=n\operatorname{rank}\mathbf{A} = n.

Proof. Statements (ii) and (iii) are equivalent by fact 2 of Section 21.2.2.1, and (iii) and (iv) are equivalent by rank--nullity. If A\mathbf{A} is invertible and Ax=0\mathbf{A}\mathbf{x} = \mathbf{0}, multiplying on the left by A−1\mathbf{A}^{-1} gives x=A−1Ax=0\mathbf{x} = \mathbf{A}^{-1}\mathbf{A}\mathbf{x} = \mathbf{0}, so (i) implies (iii).

The converse takes more work because we must actually construct the inverse. By (iv), the column space is an nn-dimensional subspace of Rn\mathbb{R}^n, which must be all of Rn\mathbb{R}^n: appending any vector outside it to a basis of col⁡A\operatorname{col}\mathbf{A} would produce n+1n + 1 linearly independent vectors in Rn\mathbb{R}^n, which is impossible. Thus every target vector in Rn\mathbb{R}^n is reached. By (iii) and fact 3, no two inputs map to the same output. We can therefore define column jj of a matrix X\mathbf{X} to be the unique solution of Ax=ej\mathbf{A}\mathbf{x} = \mathbf{e}_j. By construction, AX=I\mathbf{A}\mathbf{X} = \mathbf{I}. To see that X\mathbf{X} also works on the left, take any x∈Rn\mathbf{x} \in \mathbb{R}^n: since A(XAx)=(AX)Ax=Ax\mathbf{A}(\mathbf{X}\mathbf{A}\mathbf{x}) = (\mathbf{A}\mathbf{X})\mathbf{A}\mathbf{x} = \mathbf{A}\mathbf{x} and no two inputs collide, we must have XAx=x\mathbf{X}\mathbf{A}\mathbf{x} = \mathbf{x}. Hence XA=I\mathbf{X}\mathbf{A} = \mathbf{I} as well, and X=A−1\mathbf{X} = \mathbf{A}^{-1}. ■\blacksquare

This immediately settles the claim left open in Section 21.2.1.3. For a square orthogonal matrix Q\mathbf{Q} (satisfying Q⊤Q=I\mathbf{Q}^\top\mathbf{Q} = \mathbf{I}), if Qc=0\mathbf{Q}\mathbf{c} = \mathbf{0}, then c=Q⊤Qc=0\mathbf{c} = \mathbf{Q}^\top\mathbf{Q}\mathbf{c} = \mathbf{0}, so ker⁡Q={0}\ker\mathbf{Q} = \{\mathbf{0}\}. By the proposition, Q\mathbf{Q} is invertible, its left inverse Q⊤\mathbf{Q}^\top must equal Q−1\mathbf{Q}^{-1}, and therefore QQ⊤=I\mathbf{Q}\mathbf{Q}^\top = \mathbf{I}.

A square matrix that has no inverse is called singular; B\mathbf{B} is our standard example. Rectangular matrices never have a two-sided inverse at all. The rank of an m×nm \times n matrix is at most min⁡(m,n)\min(m, n). When m>nm > n, the column space has dimension at most n<mn \lt m, so the map is not onto: some targets in Rm\mathbb{R}^m can never be hit. When n>mn > m, rank--nullity forces a null space of dimension at least n−m>0n - m > 0, so the map is not one-to-one: distinct inputs collide. Running a map backwards requires both properties, and the beauty of the proposition above is that for a square matrix, either one guarantees the other.

21.2.2.4 Solving Linear Systems in Practice#

The matrix inverse is an indispensable tool for algebra and proofs, yet in numerical computation we almost never form it explicitly. When you need to solve Ax=b\mathbf{A}\mathbf{x} = \mathbf{b}, use np.linalg.solve(A, b) rather than np.linalg.inv(A) @ b.

There are two main reasons: speed and accuracy. First, solve factors A\mathbf{A} once into triangular matrices (an LU factorization, costing about n3/3n^3/3 multiply--adds) and solves two fast triangular systems. Forming A−1\mathbf{A}^{-1} explicitly costs roughly n3n^3 multiply--adds, three times as much work, before you even multiply by b\mathbf{b}. Second, solve is backward stable: its computed solution is the exact solution to a slightly perturbed system whose entries differ from A\mathbf{A} and b\mathbf{b} only at the level of floating-point rounding. Consequently, its residual ∥Ax−b∥\|\mathbf{A}\mathbf{x} - \mathbf{b}\| stays on the order of machine precision times ∥A∥ ∥x∥\|\mathbf{A}\|\,\|\mathbf{x}\| (using the spectral norm of Section 1.3.4). Computing inv(A) @ b carries no such guarantee; its residual can be larger by a factor up to the condition number κ(A)\kappa(\mathbf{A}), which measures how close A\mathbf{A} is to being singular (Section 21.5.3.2).

How close a matrix sits to singularity is a property of the problem itself, not of the algorithm. In double precision (roughly sixteen decimal digits), both methods can lose up to about log⁡10κ(A)\log_{10}\kappa(\mathbf{A}) digits of accuracy in the solution x\mathbf{x}. That is a worst-case bound rather than an exact prediction for any single right-hand side, so let us see how close a notorious example comes to it. The Hilbert matrix, with entries hij=1/(i+j−1)h_{ij} = 1/(i + j - 1), is a classic test case of a nearly singular matrix. We take xtrue=1\mathbf{x}_{\textrm{true}} = \mathbf{1}, form b=H1\mathbf{b} = \mathbf{H}\mathbf{1} for the 10×1010 \times 10 Hilbert matrix H\mathbf{H}, and attempt to recover x\mathbf{x} both ways.

H = 1 / (np.arange(10)[:, None] + np.arange(10) + 1)   # Hilbert matrix
x_true = np.ones(10)
b = H @ x_true
for x in (np.linalg.solve(H, b), np.linalg.inv(H) @ b):
    print(f'residual {np.linalg.norm(H @ x - b):.1e}, '
          f'error {np.linalg.norm(x - x_true):.1e}')
np.linalg.cond(H)
residual 5.7e-16, error 2.7e-04
residual 4.8e-05, error 9.0e-03
np.float64(16024416987428.36)

The condition number is κ(H)≈1.6⋅1013\kappa(\mathbf{H}) \approx 1.6 \cdot 10^{13}, warning us that up to thirteen digits can vanish. As promised, solve keeps its residual near machine precision, while inv suffers a residual roughly eleven orders of magnitude larger, right in line with the factor κ\kappa. Notice, however, that a tiny residual does not guarantee an accurate solution. Both routes lose twelve or more of the sixteen digits, approaching the worst-case bound, with inv still worse by more than an order of magnitude.

Sparse matrices add a third, decisive reason never to invert. A million-by-million matrix with only five million nonzero entries fits comfortably in memory, whereas its inverse is typically completely dense, requiring roughly 101210^{12} entries.

21.2.3 The Determinant#

21.2.3.1 Area of a Parallelogram#

By what factor does a matrix scale areas? Look back at Figure 21.2.1: our running matrix A\mathbf{A} sends the unit square (edges e1\mathbf{e}_1 and e2\mathbf{e}_2, area 11) to the parallelogram with edges a1=(1,−1)\mathbf{a}_1 = (1, -1) and a2=(2,3)\mathbf{a}_2 = (2, 3) and corners (0,0)(0, 0), (1,−1)(1, -1), (3,2)(3, 2), and (2,3)(2, 3). That parallelogram sits snugly inside the bounding box [0,3]×[−1,3][0, 3] \times [-1, 3] of area 1212. The unused portion of the box consists of four right triangles with legs 11 and 11, 22 and 33, 11 and 11, and 22 and 33, whose areas sum to 12+3+12+3=7\tfrac12 + 3 + \tfrac12 + 3 = 7. Subtracting leaves an area of 12−7=512 - 7 = 5 (Figure 21.2.6, panel (a)). The matrix A\mathbf{A} multiplies the area of the unit square by 55.

Figure 21.2.6:

The image of the unit square under A\mathbf{A} has area 55. (a) Bounding-box method: the box [0,3]×[−1,3][0, 3] \times [-1, 3] of area 1212 minus four right triangles of total area 77. (b) Base times height: the base a1=(1,−1)\mathbf{a}_1 = (1, -1) has length 2\sqrt{2}, the unit normal n=(1,1)/2\mathbf{n} = (1, 1)/\sqrt{2} is perpendicular to it, and the height of a2=(2,3)\mathbf{a}_2 = (2, 3) above the base line is a2⋅n=5/2\mathbf{a}_2\cdot\mathbf{n} = 5/\sqrt{2}.

Carving out triangles works for one picture, but every new arrangement of corners would need a new diagram. Base times height handles every case in one stroke. Let the parallelogram have edges u=(p,r)\mathbf{u} = (p, r) and w=(q,s)\mathbf{w} = (q, s), the two columns of a general 2×22 \times 2 matrix. Its base has length ∥u∥\|\mathbf{u}\|. Rotating u\mathbf{u} counter-clockwise by 90∘90^\circ gives R90u=(−r,p)\mathbf{R}_{90}\mathbf{u} = (-r, p), so

n=(−r,p)∥u∥\mathbf{n} = \frac{(-r, p)}{\|\mathbf{u}\|}

is a unit vector perpendicular to the base. From Section 21.1, the signed component of w\mathbf{w} along a unit vector n\mathbf{n} is the dot product w⋅n\mathbf{w}\cdot\mathbf{n}. Geometrically, this is the height of the parallelogram above its base, equipped with a sign: positive when w\mathbf{w} lies on the counter-clockwise side of u\mathbf{u}, and negative when it lies on the clockwise side. Multiplying base by signed height gives

∥u∥ (w⋅n)=∥u∥ −qr+ps∥u∥=ps−qr.\|\mathbf{u}\|\,(\mathbf{w}\cdot\mathbf{n}) = \|\mathbf{u}\|\,\frac{-qr + ps}{\|\mathbf{u}\|} = ps - qr.

Conveniently, the lengths ∥u∥\|\mathbf{u}\| cancel out, leaving a clean polynomial in the four matrix entries with no sign cases to split. For our running matrix, ∥u∥=2\|\mathbf{u}\| = \sqrt{2}, n=(1,1)/2\mathbf{n} = (1, 1)/\sqrt{2}, and w⋅n=5/2\mathbf{w}\cdot\mathbf{n} = 5/\sqrt{2}, giving a signed area of 55 (panel (b)), positive because a2\mathbf{a}_2 lies counter-clockwise from a1\mathbf{a}_1.

We define the determinant of a 2×22 \times 2 matrix to be this signed area of the image of the unit square:

det⁡[pqrs]=ps−qr.(21.2.6)\det\begin{bmatrix} p & q \\ r & s \end{bmatrix} = ps - qr. \tag{21.2.6}

Its magnitude ∣det⁡A∣|\det\mathbf{A}| is the factor by which the map scales area, and its sign records whether the images of e1\mathbf{e}_1 and e2\mathbf{e}_2 preserve their counter-clockwise orientation. For A\mathbf{A}, we get 1⋅3−2⋅(−1)=51 \cdot 3 - 2 \cdot (-1) = 5. Swapping the two columns of A\mathbf{A} produces (213−1)\left(\begin{smallmatrix}2 & 1\\ 3 & -1\end{smallmatrix}\right), which spans the exact same parallelogram with its edges listed in the reverse order, and its determinant flips sign to −2−3=−5-2 - 3 = -5. For the singular matrix B\mathbf{B}, we get 2⋅2−1⋅4=02 \cdot 2 - 1 \cdot 4 = 0: the unit square flattens onto the line segment from 0\mathbf{0} to (3,6)(3, 6), which has zero area.

Figure 21.2.7 contrasts all three regimes: a positive determinant preserves orientation, a negative determinant reverses it, and a zero determinant collapses the square.

Figure 21.2.7:

The determinant as signed area for our three 2×22 \times 2 examples. The unit square (dashed) maps to the region spanned by the columns. (a) A\mathbf{A}, with determinant 55: the columns keep their counter-clockwise order (curved arrow). (b) A\mathbf{A} with its columns swapped, determinant −5-5: the same parallelogram with reversed orientation. (c) B\mathbf{B}, determinant 00: the square collapses onto a segment of the line y=2xy = 2x. Panel (c) is drawn at half the scale of (a) and (b).

Base times height gives us the plane. To move to nn dimensions, we need the signed volume of an nn-dimensional box.

21.2.3.2 The Determinant in General#

How do we define the signed volume of the box spanned by nn columns in Rn\mathbb{R}^n? Rather than trying to compute high-dimensional volumes by chopping up shapes, we take a cleaner route: we write down the three geometric properties any signed volume must satisfy, and let those properties uniquely determine the formula. Viewed as a function of the columns a1,…,an\mathbf{a}_1, \ldots, \mathbf{a}_n of an n×nn \times n matrix, the determinant is:

  1. Multilinear: linear in each column separately while the other columns are held fixed. (Scaling one edge of a box scales its volume by the same factor; writing one edge as a sum splits the volume accordingly.)
  2. Alternating: equal to zero whenever two columns are identical. (When two edges coincide, the box collapses into a lower-dimensional slab of zero volume.)
  3. Normalized: det⁡I=1\det \mathbf{I} = 1. (The unit cube has volume 11.)

Check that our 2×22 \times 2 formula ps−qrps - qr satisfies all three: it is linear in (p,r)(p, r) and in (q,s)(q, s), it vanishes whenever (p,r)=(q,s)(p, r) = (q, s), and it equals 11 on I\mathbf{I}. Two powerful consequences follow immediately from these three axioms alone: a rule for swapping columns, and an explicit formula proving that at most one function can satisfy all three.

First, swapping any two columns flips the sign of the determinant. To see why, place u+w\mathbf{u} + \mathbf{w} in two column slots and expand using multilinearity:

0=det⁡(…,u+w,…,u+w,…)=det⁡(…,u,…,u,…)+det⁡(…,u,…,w,…)+det⁡(…,w,…,u,…)+det⁡(…,w,…,w,…).\begin{aligned} 0 &= \det(\ldots, \mathbf{u}+\mathbf{w}, \ldots, \mathbf{u}+\mathbf{w}, \ldots) \\ &= \det(\ldots, \mathbf{u}, \ldots, \mathbf{u}, \ldots) + \det(\ldots, \mathbf{u}, \ldots, \mathbf{w}, \ldots) \\ &\quad + \det(\ldots, \mathbf{w}, \ldots, \mathbf{u}, \ldots) + \det(\ldots, \mathbf{w}, \ldots, \mathbf{w}, \ldots). \end{aligned}

The left-hand side, the first term, and the last term all have two identical columns, so they vanish by the alternating property. What remains is

det⁡(…,u,…,w,…)=−det⁡(…,w,…,u,…).\det(\ldots, \mathbf{u}, \ldots, \mathbf{w}, \ldots) = -\det(\ldots, \mathbf{w}, \ldots, \mathbf{u}, \ldots).

Exchanging two edges of the box reverses its orientation, just as we saw in panel (b) of Figure 21.2.7.

Second, the three properties completely determine a formula. Expand each column in the standard basis as aj=∑iaij ei\mathbf{a}_j = \sum_i a_{ij}\,\mathbf{e}_i and apply multilinearity column by column. This turns det⁡A\det\mathbf{A} into a large sum of terms ai11ai22⋯ainn det⁡(ei1,…,ein)a_{i_1 1} a_{i_2 2} \cdots a_{i_n n}\, \det(\mathbf{e}_{i_1}, \ldots, \mathbf{e}_{i_n}), one for every choice of a row index iji_j in each column jj. Whenever two chosen row indices are equal, the term vanishes by the alternating property. When all nn row indices are distinct, the list ei1,…,ein\mathbf{e}_{i_1}, \ldots, \mathbf{e}_{i_n} is just a reordering of the columns of I\mathbf{I}, so repeated column swaps reduce det⁡(ei1,…,ein)\det(\mathbf{e}_{i_1}, \ldots, \mathbf{e}_{i_n}) to ±1\pm 1.

In the 2×22 \times 2 case, with columns a1=p e1+r e2\mathbf{a}_1 = p\,\mathbf{e}_1 + r\,\mathbf{e}_2 and a2=q e1+s e2\mathbf{a}_2 = q\,\mathbf{e}_1 + s\,\mathbf{e}_2, the expansion has four terms. The two with a repeated basis vector drop out, leaving

det⁡(a1,a2)=ps det⁡(e1,e2)+rq det⁡(e2,e1)=ps−qr,\det(\mathbf{a}_1, \mathbf{a}_2) = ps\,\det(\mathbf{e}_1, \mathbf{e}_2) + rq\,\det(\mathbf{e}_2, \mathbf{e}_1) = ps - qr,

recovering the signed area we derived by hand. In general, det⁡A\det\mathbf{A} is a signed sum over all ways of picking one entry from every row and every column. Writing σ(j)\sigma(j) for the row chosen in column jj, we obtain the permutation formula:

det⁡A=∑σsgn⁡(σ) aσ(1)1 aσ(2)2⋯aσ(n)n,(21.2.7)\det\mathbf{A} = \sum_{\sigma} \operatorname{sgn}(\sigma)\, a_{\sigma(1)1}\, a_{\sigma(2)2} \cdots a_{\sigma(n)n}, \tag{21.2.7}

where σ\sigma ranges over all n!n! permutations of {1,…,n}\{1, \ldots, n\}, and sgn⁡(σ)=det⁡(eσ(1),…,eσ(n))\operatorname{sgn}(\sigma) = \det(\mathbf{e}_{\sigma(1)}, \ldots, \mathbf{e}_{\sigma(n)}) is +1+1 if σ\sigma requires an even number of swaps and −1-1 if it requires an odd number. Because any function satisfying the three axioms must equal this formula, there can be at most one determinant.

We do not prove existence in full here. The subtle point is that sgn⁡(σ)\operatorname{sgn}(\sigma) is well defined (no permutation can be built from both an even and an odd number of swaps), a standard fact we take from (Horn and Johnson, 2012). Once that parity fact is in hand, the formula satisfies all three axioms: each term contains one entry from each column (giving multilinearity), only the identity permutation survives for I\mathbf{I} (giving normalization), and the alternating property follows from the same parity argument (which we omit).

Notice that normalization entered only at the very end of the derivation. That observation gives us a sharper tool that we will use in the next subsection: if ff is any multilinear and alternating function of the columns, the same swap rule and expansion apply, turning every factor f(eσ(1),…,eσ(n))f(\mathbf{e}_{\sigma(1)}, \ldots, \mathbf{e}_{\sigma(n)}) into sgn⁡(σ) f(I)\operatorname{sgn}(\sigma)\,f(\mathbf{I}). Consequently,

f(A)=f(I) det⁡A.f(\mathbf{A}) = f(\mathbf{I})\,\det\mathbf{A}.

In short, every multilinear alternating function of the columns is just a scalar multiple of the determinant.

For small hand calculations, grouping the terms of (21.2.7) by the row picked in column 11 produces the cofactor expansion: each entry ai1a_{i1} multiplies the determinant of the (n−1)×(n−1)(n-1) \times (n-1) submatrix formed by deleting row ii and column 11, weighted by the alternating sign (−1)i+1(-1)^{i+1}. For the 3×33 \times 3 matrix

M=[210131012],\mathbf{M} = \begin{bmatrix} 2 & 1 & 0 \\ 1 & 3 & 1 \\ 0 & 1 & 2 \end{bmatrix},

expanding along the first column gives

det⁡M=2det⁡[3112]−1det⁡[1012]+0det⁡[1031]=2⋅5−1⋅2+0=8.(21.2.8)\begin{aligned} \det \mathbf{M} &= 2 \det \begin{bmatrix} 3 & 1 \\ 1 & 2 \end{bmatrix} - 1 \det \begin{bmatrix} 1 & 0 \\ 1 & 2 \end{bmatrix} + 0 \det \begin{bmatrix} 1 & 0 \\ 3 & 1 \end{bmatrix} \\ &= 2 \cdot 5 - 1 \cdot 2 + 0 = 8. \end{aligned} \tag{21.2.8}

Thus M\mathbf{M} maps the unit cube in R3\mathbb{R}^3 to a box of volume 88.

For a triangular matrix, the determinant simplifies dramatically: it is just the product of the diagonal entries. Of all the rules for computing determinants, this is the one to remember. Suppose U\mathbf{U} is upper triangular, so uij=0u_{ij} = 0 whenever i>ji > j. In the permutation formula, a nonzero term must pick one entry from every column, all in distinct rows. From column 11, the only nonzero entry sits in row 11. From column 22, row 11 is already taken and rows 3,…,n3, \ldots, n are zero, forcing us to pick row 22. Continuing across the columns, only the diagonal permutation survives, and it requires zero swaps, so

det⁡U=u11u22⋯unn.\det \mathbf{U} = u_{11} u_{22} \cdots u_{nn}.

Running the same argument backwards from column nn covers lower triangular matrices. Better still, it extends to blocks. Consider a block upper triangular matrix (D1∗0D2)\left(\begin{smallmatrix}\mathbf{D}_1 & *\\ \mathbf{0} & \mathbf{D}_2\end{smallmatrix}\right) whose square diagonal blocks D1\mathbf{D}_1 and D2\mathbf{D}_2 need not be triangular themselves. Any nonzero permutation term must pick its entries in the columns of D1\mathbf{D}_1 from the rows of D1\mathbf{D}_1, because everything underneath is zero. That consumes all rows of D1\mathbf{D}_1, forcing the remaining columns to pick from the rows of D2\mathbf{D}_2; the off-diagonal block ∗* never contributes at all. Every surviving permutation splits into a pair of independent permutations on the two blocks, their signs multiply, and the sum factors cleanly:

det⁡[D1∗0D2]=det⁡D1 det⁡D2.\det\begin{bmatrix}\mathbf{D}_1 & *\\ \mathbf{0} & \mathbf{D}_2\end{bmatrix} = \det\mathbf{D}_1\,\det\mathbf{D}_2 .

Figure 21.2.8 marks the entries that survive in each case.

Figure 21.2.8:

Entries that enter the determinant. (a) In an upper triangular matrix, the zeros below the diagonal rule out every permutation except the diagonal one, so the determinant is the product of the diagonal entries. (b) In a block upper triangular matrix, the zero block confines every surviving permutation to the diagonal blocks D1\mathbf{D}_1 and D2\mathbf{D}_2. The entries marked ∗* never enter.

These two rules are essential in modern machine learning, not just in hand calculations. A normalizing flow transforms a simple random variable through an invertible neural network and must evaluate the log-determinant of the network's Jacobian at every step, because a change of variables divides the probability density by the local volume scaling factor (Section 24.2.3.1). Flows are therefore designed so that each layer has a triangular or block-triangular Jacobian: the log-determinant then reduces to a sum of nn scalar logarithms, avoiding the roughly n3/3n^3/3 multiply--adds required for a general matrix.

Another useful symmetry is that transposing leaves the determinant unchanged: det⁡A⊤=det⁡A\det\mathbf{A}^\top = \det\mathbf{A}. In the permutation formula for A⊤\mathbf{A}^\top, each term is sgn⁡(σ)∏jajσ(j)\operatorname{sgn}(\sigma)\prod_j a_{j\sigma(j)}. Setting j=σ−1(i)j = \sigma^{-1}(i) rewrites the product as ∏iaσ−1(i) i\prod_i a_{\sigma^{-1}(i)\, i}, which is the term for A\mathbf{A} corresponding to the inverse permutation σ−1\sigma^{-1}. Since undoing a sequence of swaps takes the exact same number of swaps, sgn⁡(σ−1)=sgn⁡(σ)\operatorname{sgn}(\sigma^{-1}) = \operatorname{sgn}(\sigma). The two sums therefore contain the exact same terms, which means every statement about columns of a determinant applies equally well to rows.

With n!n! terms, the permutation formula is strictly a theoretical tool and is never used numerically beyond tiny matrices. Libraries compute determinants by factoring the matrix into triangular factors (as in solve) and multiplying their diagonal entries, adjusting the sign for any row exchanges, at a cost of roughly n3/3n^3/3 multiply--adds.

21.2.3.3 Multiplicativity#

If B\mathbf{B} scales areas by det⁡B\det\mathbf{B} and A\mathbf{A} scales them by det⁡A\det\mathbf{A}, then applying B\mathbf{B} followed by A\mathbf{A} should scale areas by the product of the two factors. Let us check two examples. For our running matrix, A2=(−18−47)\mathbf{A}^2 = \left(\begin{smallmatrix}-1 & 8\\ -4 & 7\end{smallmatrix}\right), which has det⁡A2=−7+32=25=52\det\mathbf{A}^2 = -7 + 32 = 25 = 5^2. For the composite of Section 21.2.1.2, det⁡(R90T)=0⋅1−(−1)⋅1=1\det(\mathbf{R}_{90}\mathbf{T}) = 0 \cdot 1 - (-1) \cdot 1 = 1, matching det⁡R90⋅det⁡T=1⋅1\det\mathbf{R}_{90} \cdot \det\mathbf{T} = 1 \cdot 1.

A simple tiling picture explains why this should hold in general. Cover any planar region with a fine grid of tiny squares. Because a linear map acts uniformly across space, it carries every square to a parallelogram whose area is ∣det⁡A∣|\det\mathbf{A}| times that of the original square. Consequently, a linear map scales the area of every shape by ∣det⁡A∣|\det\mathbf{A}|. Applying B\mathbf{B} to a region of area VV produces area ∣det⁡B∣ V|\det\mathbf{B}|\,V, and applying A\mathbf{A} next scales it to ∣det⁡A∣ ∣det⁡B∣ V|\det\mathbf{A}|\,|\det\mathbf{B}|\,V. Since the composite AB\mathbf{A}\mathbf{B} is itself a single linear map, its scaling factor must be this product. Using the characterization from Section 21.2.3.2, we can turn that intuition into a three-line proof that handles the signs as well.

Proposition (multiplicativity of the determinant). For square matrices A\mathbf{A} and B\mathbf{B} of the same size,

det⁡(AB)=det⁡(A) det⁡(B).(21.2.9)\det(\mathbf{A}\mathbf{B}) = \det(\mathbf{A})\,\det(\mathbf{B}). \tag{21.2.9}

Proof. Fix A\mathbf{A} and treat D(B)=det⁡(AB)D(\mathbf{B}) = \det(\mathbf{A}\mathbf{B}) as a function of the columns of B\mathbf{B}. By Section 21.2.1.2, column jj of AB\mathbf{A}\mathbf{B} is Abj\mathbf{A}\mathbf{b}_j. Because A\mathbf{A} is linear and det⁡\det is multilinear, DD is multilinear in the columns of B\mathbf{B}. If two columns of B\mathbf{B} coincide, the matching columns of AB\mathbf{A}\mathbf{B} coincide too, so D(B)=0D(\mathbf{B}) = 0 and DD is alternating. Every multilinear alternating function of the columns is a scalar multiple of the determinant (Section 21.2.3.2), which gives

det⁡(AB)=D(B)=D(I) det⁡(B)=det⁡(A) det⁡(B).■\det(\mathbf{A}\mathbf{B}) = D(\mathbf{B}) = D(\mathbf{I})\,\det(\mathbf{B}) = \det(\mathbf{A})\,\det(\mathbf{B}). \qquad \blacksquare

Four consequences of (21.2.9) appear repeatedly throughout the rest of this chapter:

  1. Determinants commute even when matrices do not. Because determinants are ordinary scalars, det⁡(AB)=det⁡A det⁡B=det⁡B det⁡A=det⁡(BA)\det(\mathbf{A}\mathbf{B}) = \det\mathbf{A}\,\det\mathbf{B} = \det\mathbf{B}\,\det\mathbf{A} = \det(\mathbf{B}\mathbf{A}). For our rotation and shear, R90T≠TR90\mathbf{R}_{90}\mathbf{T} \neq \mathbf{T}\mathbf{R}_{90}, yet both products have determinant 11.
  2. Similarity invariance. For any invertible matrix V\mathbf{V}, applying consequence 1 to the factors VA\mathbf{V}\mathbf{A} and V−1\mathbf{V}^{-1} gives det⁡(VAV−1)=det⁡(V−1VA)=det⁡A\det(\mathbf{V}\mathbf{A}\mathbf{V}^{-1}) = \det(\mathbf{V}^{-1}\mathbf{V}\mathbf{A}) = \det\mathbf{A}. The matrix VAV−1\mathbf{V}\mathbf{A}\mathbf{V}^{-1} is simply the map A\mathbf{A} written in the coordinate system whose axes are the columns of V−1\mathbf{V}^{-1}, and changing coordinates cannot alter the volume scaling factor.
  3. Inverses. If A\mathbf{A} is invertible, setting B=A−1\mathbf{B} = \mathbf{A}^{-1} yields det⁡A det⁡A−1=det⁡I=1\det\mathbf{A}\,\det\mathbf{A}^{-1} = \det\mathbf{I} = 1. Therefore every invertible matrix satisfies det⁡A≠0\det\mathbf{A} \neq 0 and det⁡A−1=1/det⁡A\det\mathbf{A}^{-1} = 1/\det\mathbf{A} (for our running matrix, 1/5=0.21/5 = 0.2).
  4. Orthogonal matrices. Combining multiplicativity with det⁡Q⊤=det⁡Q\det\mathbf{Q}^\top = \det\mathbf{Q} on Q⊤Q=I\mathbf{Q}^\top\mathbf{Q} = \mathbf{I} gives
det⁡(Q)2=det⁡(Q⊤)det⁡(Q)=det⁡(Q⊤Q)=det⁡(I)=1,\det(\mathbf{Q})^2 = \det(\mathbf{Q}^\top)\det(\mathbf{Q}) = \det(\mathbf{Q}^\top\mathbf{Q}) = \det(\mathbf{I}) = 1,

so det⁡Q=±1\det\mathbf{Q} = \pm 1. Rigid motions never change volume, and the sign distinguishes orientation-preserving rotations (det⁡=+1\det = +1) from orientation-reversing reflections (det⁡=−1\det = -1) in the plane (Section 21.2.1.3).

21.2.3.4 Invertibility and the Determinant#

The determinant adds a fifth equivalent condition to the invertibility theorem of Section 21.2.2.3, and it is the only one expressed as a single number. In two dimensions the equivalence is immediate: the signed area ps−qrps - qr vanishes if and only if the two columns lie on the same line through the origin (or one of them is 0\mathbf{0}), which is to say, if and only if the columns are linearly dependent. The same holds in every dimension.

Proposition (invertibility and the determinant). An n×nn \times n matrix A\mathbf{A} is invertible if and only if det⁡A≠0\det\mathbf{A} \neq 0. Equivalently, det⁡A=0\det\mathbf{A} = 0 if and only if the columns of A\mathbf{A} are linearly dependent.

Proof. If A\mathbf{A} is invertible, then det⁡A det⁡A−1=1\det\mathbf{A}\,\det\mathbf{A}^{-1} = 1 by consequence 3 of multiplicativity, so det⁡A≠0\det\mathbf{A} \neq 0. Conversely, suppose A\mathbf{A} is not invertible. By the proposition in Section 21.2.2.3, its columns are linearly dependent, so some column is a combination of the others: aj=∑i≠jciai\mathbf{a}_j = \sum_{i \neq j} c_i\mathbf{a}_i. Expanding column jj by multilinearity gives det⁡A=∑i≠jcidet⁡(…,ai,…)\det\mathbf{A} = \sum_{i \neq j} c_i\det(\ldots, \mathbf{a}_i, \ldots), where ai\mathbf{a}_i now appears both in slot ii and in slot jj. Every term has two identical columns and therefore vanishes by the alternating property. ■\blacksquare

For our running matrix, det⁡A=5≠0\det\mathbf{A} = 5 \neq 0 certifies invertibility; for B\mathbf{B}, det⁡B=0\det\mathbf{B} = 0 confirms singularity. Keep in mind, however, what this theorem does not promise: a nonzero determinant guarantees that A−1\mathbf{A}^{-1} exists mathematically, not that it is safe to compute numerically (Section 21.2.3.6).

21.2.3.5 Block Matrices and Low-Rank Updates#

Often we already know the inverse of a part of a matrix: of one block, or of the matrix as it was before a small change. Can we reuse it? The answer comes from a single step of elimination, carried out on blocks instead of numbers. Split a square matrix M\mathbf{M} into four blocks M11\mathbf{M}_{11}, M12\mathbf{M}_{12}, M21\mathbf{M}_{21}, and M22\mathbf{M}_{22}, with M11\mathbf{M}_{11} square and invertible. Subtracting M21M11−1\mathbf{M}_{21}\mathbf{M}_{11}^{-1} times the first block row from the second clears the lower-left block, and the same step on the columns clears the upper-right one. Written as a product, this reads

[M11M12M21M22]=[I0M21M11−1I][M1100S][IM11−1M120I],S=M22−M21M11−1M12,(21.2.10)\begin{bmatrix}\mathbf{M}_{11} & \mathbf{M}_{12}\\ \mathbf{M}_{21} & \mathbf{M}_{22}\end{bmatrix} = \begin{bmatrix}\mathbf{I} & \mathbf{0}\\ \mathbf{M}_{21}\mathbf{M}_{11}^{-1} & \mathbf{I}\end{bmatrix} \begin{bmatrix}\mathbf{M}_{11} & \mathbf{0}\\ \mathbf{0} & \mathbf{S}\end{bmatrix} \begin{bmatrix}\mathbf{I} & \mathbf{M}_{11}^{-1}\mathbf{M}_{12}\\ \mathbf{0} & \mathbf{I}\end{bmatrix}, \qquad \mathbf{S} = \mathbf{M}_{22} - \mathbf{M}_{21}\mathbf{M}_{11}^{-1}\mathbf{M}_{12}, \tag{21.2.10}

as multiplying out the three factors confirms. The matrix S\mathbf{S} is the Schur complement of M11\mathbf{M}_{11}: it is what remains of M22\mathbf{M}_{22} once the first block has been eliminated. For our running matrix with 1×11 \times 1 blocks, S=3−(−1)⋅1−1⋅2=5\mathbf{S} = 3 - (-1) \cdot 1^{-1} \cdot 2 = 5.

Both outer factors are triangular with ones on the diagonal, so each has determinant 11. Multiplicativity and the block rule then give det⁡M=det⁡M11 det⁡S\det\mathbf{M} = \det\mathbf{M}_{11}\,\det\mathbf{S} (in the example, 1⋅51 \cdot 5), and M\mathbf{M} is invertible if and only if S\mathbf{S} is. An outer factor is inverted by flipping the sign of its off-diagonal block. Inverting the three factors in reverse order therefore yields

M−1=[I−M11−1M120I][M11−100S−1][I0−M21M11−1I].(21.2.11)\mathbf{M}^{-1} = \begin{bmatrix}\mathbf{I} & -\mathbf{M}_{11}^{-1}\mathbf{M}_{12}\\ \mathbf{0} & \mathbf{I}\end{bmatrix} \begin{bmatrix}\mathbf{M}_{11}^{-1} & \mathbf{0}\\ \mathbf{0} & \mathbf{S}^{-1}\end{bmatrix} \begin{bmatrix}\mathbf{I} & \mathbf{0}\\ -\mathbf{M}_{21}\mathbf{M}_{11}^{-1} & \mathbf{I}\end{bmatrix}. \tag{21.2.11}

The lower-right block of M−1\mathbf{M}^{-1} is simply S−1\mathbf{S}^{-1}, and the upper-left block is M11−1+M11−1M12S−1M21M11−1\mathbf{M}_{11}^{-1} + \mathbf{M}_{11}^{-1}\mathbf{M}_{12}\mathbf{S}^{-1}\mathbf{M}_{21}\mathbf{M}_{11}^{-1}. Nothing forces us to start in the upper-left corner, however. Eliminating M22\mathbf{M}_{22} first exchanges the roles of the blocks, and the upper-left block of M−1\mathbf{M}^{-1} then appears as the inverse of the other Schur complement, M11−M12M22−1M21\mathbf{M}_{11} - \mathbf{M}_{12}\mathbf{M}_{22}^{-1}\mathbf{M}_{21}. That matrix returns as the conditional covariance of a Gaussian in Section 24.3.3.3.

The two expressions for the upper-left block must agree, and this is surprisingly useful. Suppose that we know A−1\mathbf{A}^{-1} for an n×nn \times n matrix A\mathbf{A}, and that A\mathbf{A} then changes by a matrix of rank kk, which we write as UW⊤\mathbf{U}\mathbf{W}^\top with U,W∈Rn×k\mathbf{U}, \mathbf{W} \in \mathbb{R}^{n \times k}. Choose the blocks M11=A\mathbf{M}_{11} = \mathbf{A}, M12=−U\mathbf{M}_{12} = -\mathbf{U}, M21=W⊤\mathbf{M}_{21} = \mathbf{W}^\top, and M22=Ik\mathbf{M}_{22} = \mathbf{I}_k. One Schur complement is then A+UW⊤\mathbf{A} + \mathbf{U}\mathbf{W}^\top, and the other is the k×kk \times k matrix Ik+W⊤A−1U\mathbf{I}_k + \mathbf{W}^\top\mathbf{A}^{-1}\mathbf{U}. Equating the two upper-left blocks gives the Woodbury identity

(A+UW⊤)−1=A−1−A−1U (Ik+W⊤A−1U)−1 W⊤A−1.(21.2.12)(\mathbf{A} + \mathbf{U}\mathbf{W}^\top)^{-1} = \mathbf{A}^{-1} - \mathbf{A}^{-1}\mathbf{U}\, (\mathbf{I}_k + \mathbf{W}^\top\mathbf{A}^{-1}\mathbf{U})^{-1}\, \mathbf{W}^\top\mathbf{A}^{-1}. \tag{21.2.12}

A change of rank kk in a matrix changes its inverse by a matrix of rank at most kk, and finding that change requires only a k×kk \times k inverse. With A−1\mathbf{A}^{-1} in hand, the update costs on the order of n2kn^2k multiply--adds instead of the n3n^3 of a fresh inversion. When A\mathbf{A} is diagonal, solving a system with A+UW⊤\mathbf{A} + \mathbf{U}\mathbf{W}^\top costs only on the order of nk2nk^2. The two eliminations also give two expressions for det⁡M\det\mathbf{M}, and hence det⁡(A+UW⊤)=det⁡A det⁡(Ik+W⊤A−1U)\det(\mathbf{A} + \mathbf{U}\mathbf{W}^\top) = \det\mathbf{A}\,\det(\mathbf{I}_k + \mathbf{W}^\top\mathbf{A}^{-1}\mathbf{U}). For k=1k = 1 the inner inverse is a division, and the identity is known as the Sherman--Morrison formula:

(A+uw⊤)−1=A−1−A−1u w⊤A−11+w⊤A−1u.(21.2.13)(\mathbf{A} + \mathbf{u}\mathbf{w}^\top)^{-1} = \mathbf{A}^{-1} - \frac{\mathbf{A}^{-1}\mathbf{u}\,\mathbf{w}^\top\mathbf{A}^{-1}} {1 + \mathbf{w}^\top\mathbf{A}^{-1}\mathbf{u}}. \tag{21.2.13}

This formula is why a least-squares fit can absorb or drop one example at a time: each example changes X⊤X\mathbf{X}^\top\mathbf{X} by a rank-one term. Exercise 6 applies both the determinant and the inverse to a normalizing flow.

21.2.3.6 Limits of the Determinant#

Knowing that det⁡A≠0\det\mathbf{A} \neq 0 tells us a matrix can be inverted, but it says nothing about how close the matrix is to collapsing space, or along which directions. Two stark examples make the point from opposite extremes. First, the scaled identity 0.1 I4000.1\,\mathbf{I}_{400} is as well-behaved as a matrix can be, with inverse 10 I40010\,\mathbf{I}_{400}, yet its determinant 10−40010^{-400} is so tiny that it underflows beneath the smallest positive double-precision floating-point number. Second, the extreme shear (110801)\left(\begin{smallmatrix}1 & 10^8\\ 0 & 1\end{smallmatrix}\right) has determinant 11, yet changing its lower-left entry by just 10−810^{-8} makes it singular (5).

Below, we compute both determinants (using slogdet for the first to obtain its sign and log-magnitude safely) along with the singular values of the shear. Before running the cell, guess what rank NumPy will report for the unchanged shear.

sign, logdet = np.linalg.slogdet(0.1 * np.eye(400))
print(np.linalg.det(0.1 * np.eye(400)), sign, logdet)
shear = np.array([[1.0, 1e8], [0.0, 1.0]])
print(np.linalg.det(shear), np.linalg.matrix_rank(shear),
      np.linalg.svd(shear, compute_uv=False))
shear[1, 0] = 1e-8
print(np.linalg.det(shear), np.linalg.matrix_rank(shear))
0.0 1.0 -921.0340371976151
1.0 1 [1.e+08 1.e-08]
0.0 1

As expected, det on 0.1 I4000.1\,\mathbf{I}_{400} underflows to 0.0, while slogdet computes 400ln⁡0.1≈−921.03400 \ln 0.1 \approx -921.03 effortlessly. The unchanged shear has determinant 11, and the perturbed shear has determinant 00 up to rounding, yet matrix_rank reports rank 11 for both. In exact arithmetic the unchanged shear has rank 22, but its two singular values are roughly 10810^8 and 10−810^{-8}. NumPy treats any singular value as zero once it falls below the largest singular value times the matrix size times machine precision, here 108⋅2⋅2.2⋅10−16≈4⋅10−810^8 \cdot 2 \cdot 2.2 \cdot 10^{-16} \approx 4 \cdot 10^{-8}. Even though the shear's entries are stored exactly, floating-point arithmetic with numbers of size 10810^8 introduces rounding errors around 10−810^{-8}, so numerically the shear is indistinguishable from a singular matrix.

A single number simply cannot capture how a matrix stretches and compresses space along different directions. To see those directions, we need eigenvalues and singular values. For our running matrix A\mathbf{A}, the eigenvalues are 2±i2 \pm i, whose product is 5=det⁡A5 = \det\mathbf{A} (Section 21.3), and the singular values are roughly 3.6183.618 and 1.3821.382, whose product is 5=∣det⁡A∣5 = |\det\mathbf{A}| (Section 21.5). In fact, for every square matrix, the determinant is the product of its eigenvalues (counted with multiplicity, including complex pairs), and ∣det⁡A∣|\det\mathbf{A}| is the product of its singular values. It is the ratio of the largest to the smallest singular value, not the determinant, that measures how close a matrix is to collapsing space, and finding those directional factors is our next task.

21.2.4 Summary#

A matrix is a linear map completely determined by its columns, which record where the standard coordinate axes land, and matrix multiplication is simply the composition of linear maps read from right to left. Einstein notation and einsum unify dot products, matrix products, traces, and multi-axis tensor contractions such as transformer attention under a single index rule.

Every m×nm \times n matrix defines a column space of reachable outputs and a null space of inputs sent to zero, linked by the rank--nullity theorem rank⁡A+dim⁡ker⁡A=n\operatorname{rank}\mathbf{A} + \dim\ker\mathbf{A} = n: a 256×784256 \times 784 layer necessarily erases at least 528528 input dimensions. For a square matrix, having independent columns, trivial null space, full rank, a nonzero determinant, and an inverse are all equivalent. The determinant measures the signed factor by which a map scales volume; it multiplies under composition and equals the product of the diagonal entries for any triangular matrix. One step of block elimination produces the Schur complement, which gives the determinant and the inverse of a block matrix and, through the Woodbury identity, the inverse of a matrix after a low-rank change. Still, while a nonzero determinant guarantees that an inverse exists, it cannot tell us how close a matrix is to singularity, a question that leads directly to eigenvalues and singular values.

21.2.5 Exercises#

  1. Maps that preserve angles. Rotating every embedding vector by the same orthogonal matrix leaves all cosine similarities unchanged. This problem finds every linear map with that property.

    1. Find the condition on the columns of a square matrix A\mathbf{A} under which Ae1\mathbf{A}\mathbf{e}_1 and Ae2\mathbf{A}\mathbf{e}_2 are orthogonal. Show that A=diag⁡(1,10)\mathbf{A} = \operatorname{diag}(1, 10) satisfies it but changes the angle between (1,1)(1, 1) and (1,−1)(1, -1).
    2. Suppose that an invertible A\mathbf{A} preserves the angle between every pair of nonzero vectors. Apply this to the pairs ei,ej\mathbf{e}_i, \mathbf{e}_j and ei+ej,ei−ej\mathbf{e}_i + \mathbf{e}_j, \mathbf{e}_i - \mathbf{e}_j for i≠ji \neq j to show that A⊤A=c2I\mathbf{A}^\top\mathbf{A} = c^2\mathbf{I} for some c>0c > 0, so that A=cQ\mathbf{A} = c\mathbf{Q} with Q\mathbf{Q} orthogonal. Conversely, show that every such matrix preserves all cosine similarities.
    3. Suppose instead that ∥Ax∥=∥x∥\|\mathbf{A}\mathbf{x}\| = \|\mathbf{x}\| for every x\mathbf{x}. Expand ∥x+y∥2\|\mathbf{x} + \mathbf{y}\|^2 and ∥x−y∥2\|\mathbf{x} - \mathbf{y}\|^2 to show that A\mathbf{A} preserves every dot product, and conclude that A\mathbf{A} is orthogonal.
  2. Rank of a product. A linear autoencoder sends a dd-dimensional input through a hidden layer of width k<dk \lt d, x↦W2W1x\mathbf{x} \mapsto \mathbf{W}_2\mathbf{W}_1\mathbf{x} with W1∈Rk×d\mathbf{W}_1 \in \mathbb{R}^{k \times d} and W2∈Rd×k\mathbf{W}_2 \in \mathbb{R}^{d \times k}.

    1. Let A\mathbf{A} be an m×nm \times n matrix and B\mathbf{B} an n×pn \times p matrix. Show that the column space of AB\mathbf{A}\mathbf{B} lies in the column space of A\mathbf{A}, and that the null space of B\mathbf{B} lies in the null space of AB\mathbf{A}\mathbf{B}. Use the first fact, and rank--nullity with the second, to prove rank⁡(AB)≤min⁡(rank⁡A,rank⁡B)\operatorname{rank}(\mathbf{A}\mathbf{B}) \le \min(\operatorname{rank}\mathbf{A}, \operatorname{rank}\mathbf{B}).
    2. Conclude that W2W1\mathbf{W}_2\mathbf{W}_1 has rank at most kk. What is the smallest possible dimension of its null space? What is the largest dimension of a subspace on which the autoencoder reconstructs every input exactly?
    3. Construct a 2×32 \times 3 matrix and a 3×23 \times 2 matrix, both of rank two, whose 2×22 \times 2 product has rank one.
  3. Matrices that commute with a rotation. Matrix products do not commute in general. This problem finds the exceptions for R90\mathbf{R}_{90}.

    1. Find all 2×22 \times 2 matrices X\mathbf{X} with XR90=R90X\mathbf{X}\mathbf{R}_{90} = \mathbf{R}_{90}\mathbf{X}, and show that they are (p−qqp)=pI+qR90\left(\begin{smallmatrix}p & -q\\ q & p\end{smallmatrix}\right) = p\mathbf{I} + q\mathbf{R}_{90}.
    2. Using R902=−I\mathbf{R}_{90}^2 = -\mathbf{I}, show that (pI+qR90)(rI+sR90)=(pr−qs) I+(ps+qr) R90(p\mathbf{I} + q\mathbf{R}_{90})(r\mathbf{I} + s\mathbf{R}_{90}) = (pr - qs)\,\mathbf{I} + (ps + qr)\,\mathbf{R}_{90}, so these matrices multiply like the complex numbers p+qip + qi.
    3. For (p,q)≠(0,0)(p, q) \neq (0, 0), show that pI+qR90=p2+q2 Rϕp\mathbf{I} + q\mathbf{R}_{90} = \sqrt{p^2 + q^2}\,\mathbf{R}_\phi for the angle ϕ\phi with (cos⁡ϕ,sin⁡ϕ)=(p,q)/p2+q2(\cos\phi, \sin\phi) = (p, q)/\sqrt{p^2 + q^2}, a scaled rotation. Compute its determinant, and conclude that it is invertible unless p=q=0p = q = 0.
    4. Does the running matrix A\mathbf{A} commute with R90\mathbf{R}_{90}? Compute both products.
  4. Householder reflections. Let u\mathbf{u} be a unit vector in Rn\mathbb{R}^n and H=I−2uu⊤\mathbf{H} = \mathbf{I} - 2\mathbf{u}\mathbf{u}^\top.

    1. Show that H\mathbf{H} is symmetric and orthogonal, that Hu=−u\mathbf{H}\mathbf{u} = -\mathbf{u}, and that Hx=x\mathbf{H}\mathbf{x} = \mathbf{x} for every x\mathbf{x} perpendicular to u\mathbf{u}, so that H\mathbf{H} reflects in the hyperplane with normal u\mathbf{u}.
    2. Write H=I−2P\mathbf{H} = \mathbf{I} - 2\mathbf{P} with P=uu⊤\mathbf{P} = \mathbf{u}\mathbf{u}^\top, and explain the formula with the projection onto u\mathbf{u} from Section 21.1: what does x−2Px\mathbf{x} - 2\mathbf{P}\mathbf{x} do to the component of x\mathbf{x} along u\mathbf{u}?
    3. Prove det⁡H=−1\det\mathbf{H} = -1. Extend u\mathbf{u} to an orthonormal basis, the columns of an orthogonal matrix Q=[u q2⋯qn]\mathbf{Q} = [\mathbf{u}\ \mathbf{q}_2 \cdots \mathbf{q}_n], compute Q⊤HQ\mathbf{Q}^\top\mathbf{H}\mathbf{Q}, and use multiplicativity.
    4. Find the unit vector u\mathbf{u} whose reflection sends (3,4)(3, 4) to (5,0)(5, 0) (hint: u\mathbf{u} is parallel to (3,4)−(5,0)(3, 4) - (5, 0)), write down H\mathbf{H}, and check det⁡H=−1\det\mathbf{H} = -1. Reflections of this kind, applied column by column, are how libraries factor a matrix into an orthogonal and a triangular factor.
  5. [code] Determinant and near-singularity. A square matrix is invertible if and only if its determinant is nonzero. How well does the size of the determinant measure how close a matrix is to being singular?

    1. Use multilinearity to prove det⁡(cA)=cndet⁡A\det(c\mathbf{A}) = c^n\det\mathbf{A} for an n×nn \times n matrix A\mathbf{A} and a scalar cc, and check the identity in code for the matrix M\mathbf{M} of (21.2.8) with c=2c = 2.
    2. Draw an n×nn \times n lower triangular matrix with independent standard Gaussian entries on and below the diagonal, for n=20n = 20, 100100, and 10001000. Compare the logarithm that np.linalg.slogdet returns with the sum of the logarithms of the absolute diagonal entries, which the triangular rule makes exact up to rounding. From which nn on do the two disagree, and by how much at n=1000n = 1000? Compute np.linalg.cond for n=20n = 20 and n=100n = 100, and explain the failure. (The routine does not know that the matrix is triangular. It factors it with row exchanges, like any other matrix.)
    3. The text states that a change of 10−810^{-8} in the lower left entry makes the shear (110801)\left(\begin{smallmatrix}1 & 10^8\\ 0 & 1\end{smallmatrix}\right) singular. Verify it, and show that no smaller change of a single entry does.
  6. Determinant of a rank-one update. ● A planar flow (Rezende and Mohamed, 2015) transforms z∈Rd\mathbf{z} \in \mathbb{R}^d by f(z)=z+u h(w⋅z+b)f(\mathbf{z}) = \mathbf{z} + \mathbf{u}\,h(\mathbf{w}\cdot\mathbf{z} + b) for vectors u,w\mathbf{u}, \mathbf{w}, a scalar bb, and a scalar nonlinearity hh. Computing the density of f(z)f(\mathbf{z}) requires the determinant of the Jacobian I+h′(w⋅z+b) uw⊤\mathbf{I} + h'(\mathbf{w}\cdot\mathbf{z} + b)\,\mathbf{u}\mathbf{w}^\top.

    1. Use multilinearity and the alternating property to show det⁡(uw⊤)=0\det(\mathbf{u}\mathbf{w}^\top) = 0 for n×nn \times n matrices with n≥2n \ge 2.
    2. Verify the two factorizations
[I−uw⊤1]=[I0w⊤1][I−u0⊤1+w⋅u]=[I−u0⊤1][I+uw⊤0w⊤1].\begin{aligned}\begin{bmatrix}\mathbf{I} & -\mathbf{u}\\ \mathbf{w}^\top & 1\end{bmatrix} &= \begin{bmatrix}\mathbf{I} & \mathbf{0}\\ \mathbf{w}^\top & 1\end{bmatrix}\begin{bmatrix}\mathbf{I} & -\mathbf{u}\\ \mathbf{0}^\top & 1 + \mathbf{w}\cdot\mathbf{u}\end{bmatrix} \\ &= \begin{bmatrix}\mathbf{I} & -\mathbf{u}\\ \mathbf{0}^\top & 1\end{bmatrix}\begin{bmatrix}\mathbf{I} + \mathbf{u}\mathbf{w}^\top & \mathbf{0}\\ \mathbf{w}^\top & 1\end{bmatrix}.\end{aligned}

Use the permutation formula (21.2.7) to show that a matrix whose last column is en+1\mathbf{e}_{n+1} has the determinant of its upper-left n×nn \times n block. Deduce det⁡(I+uw⊤)=1+w⋅u\det(\mathbf{I} + \mathbf{u}\mathbf{w}^\top) = 1 + \mathbf{w}\cdot\mathbf{u} from (21.2.9) and the triangular rule.

  1. Write the logarithm of the absolute Jacobian determinant of a planar flow, and compare the cost of evaluating it with the cost of a general d×dd \times d determinant. For h=tanh⁡h = \tanh, which values of u⋅w\mathbf{u}\cdot\mathbf{w} keep the Jacobian invertible at every z\mathbf{z}?
  2. Use the Sherman--Morrison formula (21.2.13) to write the inverse of the Jacobian I+c uw⊤\mathbf{I} + c\,\mathbf{u}\mathbf{w}^\top, where c=h′(w⋅z+b)c = h'(\mathbf{w}\cdot\mathbf{z} + b). Check that the formula breaks down at the same values of cc at which the determinant vanishes, and count the multiply--adds needed to apply the inverse to a vector. The inverse Jacobian does not invert ff itself: show that recovering z\mathbf{z} from f(z)f(\mathbf{z}) reduces to solving one scalar equation for w⋅z\mathbf{w}\cdot\mathbf{z}.
  1. [code] Einstein summation for attention. Let the query, key and value tensors have the shapes (nb,nh,nq,dh)(n_b, n_h, n_q, d_h), (nb,nh,nk,dh)(n_b, n_h, n_k, d_h) and (nb,nh,nk,dh)(n_b, n_h, n_k, d_h).
    1. Write the einsum strings for the scores sbhit=∑jqbhijkbhtjs_{bhit} = \sum_j q_{bhij}k_{bhtj} and for the weighted sum of values obhij=∑tpbhit vbhtjo_{bhij} = \sum_t p_{bhit}\,v_{bhtj}, where pbhitp_{bhit} are the attention weights, and check both against @ with swapaxes.
    2. Count the multiply--adds of each contraction as a product of the sizes. Compare them with the multiply--adds of applying one dh×dhd_h \times d_h linear map to every query, and find the number of keys nkn_k beyond which the scores cost more.
    3. Write tr⁡(A⊤A)\operatorname{tr}(\mathbf{A}^\top\mathbf{A}), tr⁡(AA⊤)\operatorname{tr}(\mathbf{A}\mathbf{A}^\top) and ∑ijaij2\sum_{ij} a_{ij}^2 as one einsum each for a random 3×53 \times 5 matrix, and check that they agree. Which of the two equalities is an instance of (21.2.2), and why does the other one hold?

Discussions