Course contents 02 / 16

02 / 16 · Linear Algebra

Matrices and linear systems

How to solve a system of linear equations: three ways to read it, Gaussian elimination as the LU factorization, when a solution exists and how many there are, and why the inverse is written but rarely computed.

On this page 12

Two equations in two unknowns are solved at school by substitution:

2x−y=1,x+y=5.\begin{aligned} 2x - y &= 1 , \\ x + y &= 5 . \end{aligned}

The second equation gives y=5−xy = 5 - x; substituting it into the first, 2x−(5−x)=12x - (5 - x) = 1, so 3x=63x = 6, x=2x = 2 and y=3y = 3. Fitting a linear model, evaluating a Gaussian density, taking a Newton step and inverting a layer of a normalizing flow all ask the same question with thousands of unknowns: given an output bb, which inputs xx satisfy Ax=bAx = b?

Substitution does not scale. With a thousand unknowns there is no obvious order in which to substitute, and no estimate of the work. It also gives no warning in advance. Replace the second equation by 4x−2y=34x - 2y = 3 and substitution ends in the contradiction 2=32 = 3; replace it by 4x−2y=24x - 2y = 2 and it ends in 2=22 = 2, true for every point of the line y=2x−1y = 2x - 1. Whether a system has no solution, one, or infinitely many is a property of the matrix and the right-hand side, and it can be computed before solving.

Three readings of Ax = b#

The system above is Ax=bAx = b with

A=(2−111),b=(15),\begin{aligned} A &= \begin{pmatrix} 2 & -1 \\ 1 & 1 \end{pmatrix}, \\ b &= \begin{pmatrix} 1 \\ 5 \end{pmatrix} , \end{aligned}

and the unknown x=(x1,x2)x = (x_1, x_2). Read by rows, each equation is a line in the plane of the unknowns, here 2x1−x2=12x_1 - x_2 = 1 and x1+x2=5x_1 + x_2 = 5, and a solution is a point on both. In Rn\mathbb R^n each equation is a hyperplane, a flat set of dimension n−1n - 1, and the solutions are their intersection. For a nonzero row a⊤a^\top, the solutions of a⊤x=0a^\top x = 0 are the kernel of a map of rank 1, of dimension n−1n - 1 by rank–nullity, and those of a⊤x=bia^\top x = b_i are that kernel shifted by one solution, as the existence section shows.

Read by columns, AxAx is the combination x1a1+x2a2x_1 a_1 + x_2 a_2 of the columns a1=(2,1)a_1 = (2, 1) and a2=(−1,1)a_2 = (-1, 1), and the question is which combination gives bb. The answer, 2a1+3a2=(1,5)2a_1 + 3a_2 = (1, 5), is the solution x=(2,3)x = (2, 3).

Read as a map, x↦Axx \mapsto Ax is linear, and the question is whether bb lies in its image and which inputs reach it. A solution exists exactly when bb is in the column space, and any two solutions differ by a vector of the kernel.

Figure

A 2 × 2 system: the row picture and the column picture

Two pictures of one system of linear equationsLeft: the lines 2x − y = 1 and x + y = 5 meet at the point (2, 3). Right: the columns a₁ = (2, 1) and a₂ = (−1, 1); a path from the origin along 2a₁ to (4, 2) and then along 3a₂ arrives at b = (1, 5).rows: two linescolumns: 2a₁ + 3a₂ = b2x − y = 1x + y = 5(2, 3)a₁a₂2a₁3a₂b = (1, 5)Two pictures of one system of linear equationsLeft: the lines 2x − y = 1 and x + y = 5 meet at the point (2, 3). Right: the columns a₁ = (2, 1) and a₂ = (−1, 1); a path from the origin along 2a₁ to (4, 2) and then along 3a₂ arrives at b = (1, 5).rows: two linescolumns: 2a₁ + 3a₂ = b2x − y = 1x + y = 5(2, 3)a₁a₂2a₁3a₂b = (1, 5)
The system 2x − y = 1, x + y = 5. Left: the two equations as lines in the (x, y) plane, meeting at (2, 3). Right: the columns a₁ = (2, 1) and a₂ = (−1, 1); going 2a₁ and then 3a₂ reaches b = (1, 5).

Elimination manipulates the rows; the columns and the map explain when a solution exists (Strang, 2016, section 1.3).

Gaussian elimination#

Elimination uses one operation: subtract a multiple of one equation from another. It does not change the set of solutions, because adding the same multiple back undoes it. The goal is to clear the entries below the diagonal, one column at a time. In column kk the diagonal entry akka_{kk} is the pivot. For each row ii below it, the multiplier ℓik=aik/akk\ell_{ik} = a_{ik}/a_{kk}, computed from the current entries, times row kk is subtracted from row ii, which makes its entry in column kk zero.

Take three equations, written as the augmented matrix [A∣b][A \mid b], which appends bb to AA as an extra column:

2x1+x2−x3=14x1+5x2−3x3=5−2x1+5x2−2x3=2,\begin{aligned} 2x_1 + x_2 - x_3 &= 1 \\ 4x_1 + 5x_2 - 3x_3 &= 5 \\ -2x_1 + 5x_2 - 2x_3 &= 2 , \end{aligned} [A∣b]=(21−1145−35−25−22).[A \mid b] = \left(\begin{array}{rrr|r} 2 & 1 & -1 & 1 \\ 4 & 5 & -3 & 5 \\ -2 & 5 & -2 & 2 \end{array}\right) .
  1. In column 1 the pivot is 22. Row 2 has the multiplier ℓ21=4/2=2\ell_{21} = 4/2 = 2, and row 2 minus twice row 1 is (0,3,−1∣3)(0, 3, -1 \mid 3). Row 3 has ℓ31=−2/2=−1\ell_{31} = -2/2 = -1, and row 3 plus row 1 is (0,6,−3∣3)(0, 6, -3 \mid 3).
  2. In column 2 the pivot is now 33. Row 3 has ℓ32=6/3=2\ell_{32} = 6/3 = 2, and row 3 minus twice row 2 is (0,0,−1∣−3)(0, 0, -1 \mid -3).
  3. The system is now upper triangular, all its entries below the diagonal being zero, and it is solved from the bottom up by back substitution:
(21−1103−1300−1−3),\left(\begin{array}{rrr|r} 2 & 1 & -1 & 1 \\ 0 & 3 & -1 & 3 \\ 0 & 0 & -1 & -3 \end{array}\right) , −x3=−3⇒ x3=3,3x2−3=3⇒ x2=2,2x1+2−3=1⇒ x1=1.\begin{aligned} -x_3 &= -3 &&\Rightarrow\ x_3 = 3 , \\ 3x_2 - 3 &= 3 &&\Rightarrow\ x_2 = 2 , \\ 2x_1 + 2 - 3 &= 1 &&\Rightarrow\ x_1 = 1 . \end{aligned}

The solution x=(1,2,3)x = (1, 2, 3) satisfies the three original equations: 2+2−3=12 + 2 - 3 = 1, 4+10−9=54 + 10 - 9 = 5 and −2+10−6=2-2 + 10 - 6 = 2. The pivots 22, 33 and −1-1 were all nonzero, which is what made each step possible.

Figure

Gaussian elimination on a 3 × 3 system, and the LU factorization it produces

Elimination steps for a 3 × 3 systemThree augmented matrices: the original, after elimination in column 1, and after elimination in column 2. Then three lines of back substitution and the factorization A = LU, where L holds the multipliers 2, −1 and 2 below a unit diagonal and U is upper triangular with pivots 2, 3 and −1.21−1145−35−25−22[A | b]121−1103−1306−33r₂ − 2r₁r₃ + r₁221−1103−1300−1−3r₃ − 2r₂pivots 2, 3, −13−x₃ = −3, x₃ = 33x₂ − 3 = 3, x₂ = 22x₁ + 2 − 3 = 1, x₁ = 14100210−12121−103−100−1A =LU5Elimination steps for a 3 × 3 systemThree augmented matrices: the original, after elimination in column 1, and after elimination in column 2. Then three lines of back substitution and the factorization A = LU, where L holds the multipliers 2, −1 and 2 below a unit diagonal and U is upper triangular with pivots 2, 3 and −1.21−1145−35−25−22[A | b]121−1103−1306−33r₂ − 2r₁, r₃ + r₁221−1103−1300−1−3r₃ − 2r₂pivots 2, 3, −13−x₃ = −3, x₃ = 33x₂ − 3 = 3, x₂ = 22x₁ + 2 − 3 = 1, x₁ = 14100210−12121−103−100−1A =LU5
The system of the text; rᵢ is row i of the augmented matrix. Each step subtracts multiples of the pivot row from the rows below it, creating the zeros in green. The multipliers 2, −1 and 2 fill L below its diagonal; U is the final triangular matrix. Press ▶ to step through.

Elimination is a factorization: A = LU#

The multipliers 2,−1,22, -1, 2 were used once and seemingly thrown away. Kept, they give a factorization of AA. Collect the multipliers of step kk in the vector ℓk=(0,…,0,ℓk+1,k,…,ℓnk)\ell_k = (0, \dots, 0, \ell_{k+1,k}, \dots, \ell_{nk}), with zeros in positions 11 to kk. Subtracting ℓik\ell_{ik} times row kk from every row i>ki \gt k is multiplication on the left by

Ek=I−ℓkek⊤,E_k = I - \ell_k e_k^\top ,

because ek⊤Me_k^\top M is row kk of MM; here II is the identity and eke_k the kk-th standard basis vector. Adding the rows back undoes the step, Ek−1=I+ℓkek⊤E_k^{-1} = I + \ell_k e_k^\top: the product (I−ℓkek⊤)(I+ℓkek⊤)(I - \ell_k e_k^\top)(I + \ell_k e_k^\top) equals I−ℓk(ek⊤ℓk) ek⊤I - \ell_k (e_k^\top \ell_k)\, e_k^\top, and ek⊤ℓk=0e_k^\top \ell_k = 0 because ℓk\ell_k has a zero in position kk. For three unknowns, elimination and its reversal read

U=E2E1A,A=E1−1E2−1 U=(I+ℓ1e1⊤)(I+ℓ2e2⊤) U=(I+ℓ1e1⊤+ℓ2e2⊤) U.\begin{aligned} U &= E_2 E_1 A , \\ A &= E_1^{-1} E_2^{-1}\, U \\ &= \big(I + \ell_1 e_1^\top\big)\big(I + \ell_2 e_2^\top\big)\, U \\ &= \big(I + \ell_1 e_1^\top + \ell_2 e_2^\top\big)\, U . \end{aligned}

Multiplying out the two brackets leaves a cross term ℓ1(e1⊤ℓ2) e2⊤\ell_1 (e_1^\top \ell_2)\, e_2^\top, which vanishes because the first entry of ℓ2\ell_2 is zero. The last bracket has ℓ1\ell_1 in column 1 and ℓ2\ell_2 in column 2 below a diagonal of ones. It is a lower triangular matrix LL, with the multiplier ℓik\ell_{ik} in row ii and column kk, and

A=LU,A = LU ,

where UU is the upper triangular matrix at the end of elimination. For any nn the same expansion of E1−1⋯En−1−1E_1^{-1} \cdots E_{n-1}^{-1} gives I+ℓ1e1⊤+⋯+ℓn−1en−1⊤I + \ell_1 e_1^\top + \dots + \ell_{n-1} e_{n-1}^\top: every product of two or more of the terms contains a factor ej⊤ℓke_j^\top \ell_k with j<kj \lt k, which is zero because ℓk\ell_k has zeros in positions 1 to kk. In the example,

(21−145−3−25−2)=(100210−121)(21−103−100−1).\begin{pmatrix} 2 & 1 & -1 \\ 4 & 5 & -3 \\ -2 & 5 & -2 \end{pmatrix} = \begin{pmatrix} 1 & 0 & 0 \\ 2 & 1 & 0 \\ -1 & 2 & 1 \end{pmatrix} \begin{pmatrix} 2 & 1 & -1 \\ 0 & 3 & -1 \\ 0 & 0 & -1 \end{pmatrix} .

Row 3 of the product is −1⋅(2,1,−1)+2⋅(0,3,−1)+1⋅(0,0,−1)=(−2,5,−2)-1 \cdot (2, 1, -1) + 2 \cdot (0, 3, -1) + 1 \cdot (0, 0, -1) = (-2, 5, -2), the third row of AA.

The factorization separates the matrix from the right-hand side. Solving Ax=bAx = b becomes two triangular solves: first Lc=bLc = b from the top down, by forward substitution, then Ux=cUx = c from the bottom up. Here c1=1c_1 = 1, then 2c1+c2=52c_1 + c_2 = 5 gives c2=3c_2 = 3, and −c1+2c2+c3=2-c_1 + 2c_2 + c_3 = 2 gives c3=−3c_3 = -3, the right-hand column that elimination produced. Once AA is factored, every new bb costs only the two triangular solves.

Row exchanges and pivoting#

Elimination needs a nonzero pivot. The system

(0111)x=(12)\begin{pmatrix} 0 & 1 \\ 1 & 1 \end{pmatrix} x = \begin{pmatrix} 1 \\ 2 \end{pmatrix}

has the solution x=(1,1)x = (1, 1), but its first pivot is zero. Exchanging the two equations fixes it. In general rows are exchanged whenever needed, and the factorization becomes PA=LUPA = LU, where the permutation matrix PP is the identity with its rows reordered. Every invertible matrix has such a factorization. A nonzero pivot can always be found: if at step kk every entry of column kk from row kk down were zero, the first kk columns of the current matrix EAEA would lie in the span of e1,…,ek−1e_1, \dots, e_{k-1} and so be dependent; some z≠0z \ne 0 would give EAz=0EAz = 0, hence Az=0Az = 0, and AA would be singular. That the exchanges made along the way can be collected into one PP in front, with the multipliers reordered inside LL, is shown in Trefethen and Bau (1997), lecture 21.

A small pivot is nearly as bad as a zero one. Replace the 00 above by 10−1710^{-17}. Without an exchange the multiplier is 101710^{17}. Double precision keeps about 16 significant digits (floating point), so the entry 1−10171 - 10^{17} rounds to −1017-10^{17}, and so does the right-hand side 2−10172 - 10^{17}. Back substitution then gives x2=1x_2 = 1 and x1=(1−1)/10−17=0x_1 = (1 - 1)/10^{-17} = 0, while the true solution is (1,1)(1, 1) to sixteen digits. The information in the second equation has been rounded away.

Partial pivoting prevents this. At each step it exchanges rows so that the pivot is the entry of largest absolute value in its column, which keeps every multiplier at most 1 in absolute value. Library routines (scipy.linalg.lu, and numpy.linalg.solve, which calls LAPACK) always pivot. On the worked example the first pivot becomes 44 instead of 22; the factors change and the solution does not. The entries of UU can still grow. One step replaces an entry by aij−ℓikakja_{ij} - \ell_{ik} a_{kj}, and with ∣ℓik∣≤1\lvert\ell_{ik}\rvert \le 1 that is at most twice the largest entry in absolute value, so n−1n - 1 steps grow the entries by a factor of at most 2n−12^{n-1}. Contrived matrices reach this bound, and practical ones almost never come close (Trefethen and Bau, 1997, lecture 22; Oseledets, 2024, lecture 5); the conditioning note shows what the size of the error depends on instead.

What elimination costs#

Step kk changes only the block below and to the right of the pivot: n−kn - k rows, each with n−kn - k entries, at one multiply–add per entry. The entries of column kk become zero by construction and are not computed. Summing over the steps, with j=n−kj = n - k,

∑k=1n−1(n−k)2=∑j=1n−1j2=(n−1) n (2n−1)6≈n33\begin{aligned} \sum_{k=1}^{n-1} (n - k)^2 &= \sum_{j=1}^{n-1} j^2 \\ &= \frac{(n - 1)\, n\, (2n - 1)}{6} \approx \frac{n^3}{3} \end{aligned}

multiply–adds for the LU factorization of an n×nn \times n matrix. The n−kn - k divisions for the multipliers add only a lower-order term. Counting the multiplication and the addition as two floating-point operations gives the 23n3\tfrac23 n^3 flops quoted by Boyd and Vandenberghe (2004, appendix C).

For the 3×33 \times 3 example the count is 22+12=52^2 + 1^2 = 5: four updated entries in step 1 and one in step 2. For n=1000n = 1000 it is 332,833,500332{,}833{,}500, close to n3/3n^3/3. Each triangular solve costs about n2/2n^2/2 multiply–adds, since row ii uses the i−1i - 1 unknowns already found and 1+2+⋯+(n−1)=n(n−1)/21 + 2 + \dots + (n - 1) = n(n - 1)/2; so with the factors at hand a new right-hand side costs n2n^2: for n=1000n = 1000, a million operations instead of a third of a billion.

Rank and the four fundamental subspaces#

Elimination works on any rectangular matrix A∈Rm×nA \in \mathbb R^{m \times n}. It produces an echelon form RR, in which each nonzero row starts with a pivot further right than the row above and zero rows come last. The rank rr is the number of pivots. Four subspaces belong to every AA:

  • the column space col⁡(A)⊆Rm\operatorname{col}(A) \subseteq \mathbb R^m, spanned by the columns: the image of x↦Axx \mapsto Ax;
  • the row space row⁡(A)=col⁡(A⊤)⊆Rn\operatorname{row}(A) = \operatorname{col}(A^\top) \subseteq \mathbb R^n, spanned by the rows;
  • the kernel (null space) ker⁡A={x:Ax=0}⊆Rn\ker A = \{x : Ax = 0\} \subseteq \mathbb R^n;
  • the left null space ker⁡A⊤={y:A⊤y=0}⊆Rm\ker A^\top = \{y : A^\top y = 0\} \subseteq \mathbb R^m, the combinations of rows that vanish, y⊤A=0y^\top A = 0.

Their dimensions are all fixed by rr:

dim⁡row⁡(A)=dim⁡col⁡(A)=r,dim⁡ker⁡A=n−r,dim⁡ker⁡A⊤=m−r.\begin{aligned} \dim \operatorname{row}(A) &= \dim \operatorname{col}(A) = r , \\ \dim \ker A &= n - r , \\ \dim \ker A^\top &= m - r . \end{aligned}

That the number of independent rows equals the number of independent columns is not obvious. A 3×1003 \times 100 matrix has at most 3 independent rows, so it has at most 3 independent columns among its hundred. Elimination is the reason: it changes neither the row space nor the kernel, and in the echelon form both counts can be read off (Strang, 2016, section 3.5). Write the elimination as R=EAR = EA, with EE invertible because every step can be undone. Then:

  1. Every row of RR is a combination of rows of AA and, since EE is invertible, the other way round, so row⁡(A)=row⁡(R)\operatorname{row}(A) = \operatorname{row}(R). The nonzero rows of RR are independent, since each has its pivot in a column where the rows below it are zero. So dim⁡row⁡(A)=r\dim \operatorname{row}(A) = r.
  2. Ax=0Ax = 0 exactly when Rx=EAx=0Rx = EAx = 0, so a combination of columns vanishes for AA exactly when the same combination vanishes for RR. In RR the rr pivot columns are independent: in a vanishing combination of them, the last pivot row is nonzero only in the last pivot column, so that coefficient is zero; the row above then clears the next coefficient, and so on up. All columns of RR have zeros below row rr, so they lie in a space of dimension rr, of which the rr pivot columns are a basis; every other column is a combination of them. The same holds for the columns of AA in the same positions. So dim⁡col⁡(A)=r\dim \operatorname{col}(A) = r.
  3. Rank–nullity (previous note) gives dim⁡ker⁡A=n−r\dim \ker A = n - r, and, for A⊤A^\top, whose rank is dim⁡col⁡(A⊤)=dim⁡row⁡(A)=r\dim \operatorname{col}(A^\top) = \dim \operatorname{row}(A) = r, it gives dim⁡ker⁡A⊤=m−r\dim \ker A^\top = m - r.

Row 2 minus twice row 1, row 3 minus three times row 1, and then row 3 minus row 2 bring a 3×43 \times 4 matrix to echelon form:

A=(120124143615),R=(120100120000).\begin{aligned} A &= \begin{pmatrix} 1 & 2 & 0 & 1 \\ 2 & 4 & 1 & 4 \\ 3 & 6 & 1 & 5 \end{pmatrix}, \\ R &= \begin{pmatrix} 1 & 2 & 0 & 1 \\ 0 & 0 & 1 & 2 \\ 0 & 0 & 0 & 0 \end{pmatrix} . \end{aligned}

There are two pivots, in columns 1 and 3, so r=2r = 2. The pivot columns of AA, (1,2,3)(1, 2, 3) and (0,1,1)(0, 1, 1), are a basis of col⁡(A)\operatorname{col}(A): column 2 is twice column 1, and column 4 is column 1 plus twice column 3. The nonzero rows of RR, (1,2,0,1)(1, 2, 0, 1) and (0,0,1,2)(0, 0, 1, 2), are a basis of row⁡(A)\operatorname{row}(A).

The kernel has dimension 4−2=24 - 2 = 2. The non-pivot unknowns x2=sx_2 = s and x4=tx_4 = t are free, and Rx=0Rx = 0 gives x3=−2tx_3 = -2t and x1=−2s−tx_1 = -2s - t, so ker⁡A\ker A is spanned by (−2,1,0,0)(-2, 1, 0, 0) and (−1,0,−2,1)(-1, 0, -2, 1). The left null space has dimension 3−2=13 - 2 = 1. Elimination showed that row 3 minus row 1 minus row 2 is zero, so it is spanned by y=(1,1,−1)y = (1, 1, -1), and indeed y⊤A=0y^\top A = 0.

The subspaces come in perpendicular pairs. Every row of AA has zero dot product with every kernel vector, since that is what Ax=0Ax = 0 says, and every column has zero dot product with every vector of the left null space. Here (1,2,0,1)⋅(−1,0,−2,1)=0(1, 2, 0, 1) \cdot (-1, 0, -2, 1) = 0 and (1,2,3)⋅(1,1,−1)=0(1, 2, 3) \cdot (1, 1, -1) = 0. The next note makes “perpendicular” precise and uses these pairs for projections.

When a solution exists, and when it is unique#

When is bb reachable? The column picture gives the first answer and the left null space gives a test:

Ax=b has a solution  ⟺   b∈col⁡(A)  ⟺   y⊤b=0 for every y∈ker⁡A⊤.\begin{aligned} & Ax = b \text{ has a solution} \\ \iff\ & b \in \operatorname{col}(A) \\ \iff\ & y^\top b = 0 \text{ for every } y \in \ker A^\top . \end{aligned}

The test is necessary: if b=Axb = Ax, then for every y∈ker⁡A⊤y \in \ker A^\top

y⊤b=y⊤Ax=(A⊤y)⊤x=0.\begin{aligned} y^\top b &= y^\top A x \\ &= (A^\top y)^\top x \\ &= 0 . \end{aligned}

It is also sufficient. Let YY have a basis of ker⁡A⊤\ker A^\top as its m−rm - r rows. The vectors bb with Yb=0Yb = 0 form a subspace of dimension m−(m−r)=rm - (m - r) = r, by rank–nullity. It contains col⁡(A)\operatorname{col}(A), by the chain above, and col⁡(A)\operatorname{col}(A) also has dimension rr, so the two coincide.

Once one solution xpx_p is known, the kernel describes all of them. If Axp=bAx_p = b and Ax=bAx = b, then A(x−xp)=0A(x - x_p) = 0, so the solutions are exactly the vectors xp+zx_p + z with z∈ker⁡Az \in \ker A.

For the 3×43 \times 4 matrix above, Ax=bAx = b is solvable exactly when b1+b2−b3=0b_1 + b_2 - b_3 = 0. For b=(1,3,4)b = (1, 3, 4) the test passes, elimination gives Rx=(1,1,0)Rx = (1, 1, 0), and with x2=x4=0x_2 = x_4 = 0 the particular solution is xp=(1,0,1,0)x_p = (1, 0, 1, 0). All solutions are xp+s(−2,1,0,0)+t(−1,0,−2,1)x_p + s(-2, 1, 0, 0) + t(-1, 0, -2, 1). For b=(1,3,5)b = (1, 3, 5) the test gives −1-1, and the last row of the eliminated system reads 0=10 = 1: no solution exists.

The rank decides which cases are possible:

shape and ranksolutions of Ax=bAx = b
r=m=nr = m = n (square, invertible)exactly one, for every bb
r=n<mr = n \lt m (tall, independent columns)none or exactly one
r=m<nr = m \lt n (wide, independent rows)infinitely many, for every bb
r<mr \lt m and r<nr \lt nnone or infinitely many

A solution exists for every bb exactly when r=mr = m, so that ker⁡A⊤={0}\ker A^\top = \{0\} and the test is empty. It is unique whenever it exists exactly when r=nr = n, so that ker⁡A={0}\ker A = \{0\}.

The inverse, and why it is rarely formed#

A square matrix with r=nr = n is invertible: there is a matrix A−1A^{-1} with A−1A=AA−1=IA^{-1}A = AA^{-1} = I, and then x=A−1bx = A^{-1} b. Why does it exist? By the table above, each system Ax=ejAx = e_j has exactly one solution; the matrix XX with these solutions as columns has AX=IAX = I. It is also a left inverse: A(XA−I)=AXA−A=0A(XA - I) = AXA - A = 0, and since ker⁡A={0}\ker A = \{0\}, every column of XA−IXA - I is zero. So a one-sided inverse of a square matrix is the inverse. Column jj of A−1A^{-1} solves Ax=ejAx = e_j, so the inverse can be computed by solving nn systems with the same LU factors. Two rules follow from the definition. The inverse of a product reverses the order, (AB)−1=B−1A−1(AB)^{-1} = B^{-1} A^{-1}, because (AB)(B−1A−1)=AA−1=I(AB)(B^{-1}A^{-1}) = AA^{-1} = I. And (A⊤)−1=(A−1)⊤(A^\top)^{-1} = (A^{-1})^\top, by transposing AA−1=IAA^{-1} = I with the rule (XY)⊤=Y⊤X⊤(XY)^\top = Y^\top X^\top, which holds entry by entry, since (XY)ji=∑kxjkyki(XY)_{ji} = \sum_k x_{jk} y_{ki}.

For 2×22 \times 2 matrices there is a formula. Swapping the diagonal entries and negating the others gives a matrix whose product with AA is a multiple of II; the four entries of the product are ad−bcad - bc, −ab+ba-ab + ba, cd−dccd - dc and −cb+da-cb + da:

(abcd)(d−b−ca)=(ad−bc) I.\begin{pmatrix} a & b \\ c & d \end{pmatrix} \begin{pmatrix} d & -b \\ -c & a \end{pmatrix} = (ad - bc)\, I .

So, when ad−bc≠0ad - bc \ne 0,

(abcd)−1=1ad−bc(d−b−ca).\begin{pmatrix} a & b \\ c & d \end{pmatrix}^{-1} = \frac{1}{ad - bc} \begin{pmatrix} d & -b \\ -c & a \end{pmatrix} .

The number ad−bcad - bc is the determinant, the subject of the next note but one. For the opening system ad−bc=3ad - bc = 3, and

A−1=13(11−12),A−1b=13(1+5−1+10)=(23).\begin{aligned} A^{-1} &= \frac13 \begin{pmatrix} 1 & 1 \\ -1 & 2 \end{pmatrix}, \\ A^{-1} b &= \frac13 \begin{pmatrix} 1 + 5 \\ -1 + 10 \end{pmatrix} = \begin{pmatrix} 2 \\ 3 \end{pmatrix} . \end{aligned}

The formula x=A−1bx = A^{-1}b is the right way to write a solution in a derivation and the wrong way to compute one (Strang, 2016, section 2.5; Boyd and Vandenberghe, 2004, appendix C). Forming A−1A^{-1} takes about n3n^3 multiply–adds, three times the LU factorization: n3/3n^3/3 for the factors, about n3/6n^3/6 for the forward solves Lc=ejLc = e_j, whose solutions begin with j−1j - 1 zeros, and n⋅n2/2n \cdot n^2/2 for the back solves. Afterwards A−1bA^{-1}b costs n2n^2, the same as the two triangular solves. Nothing is saved.

It is also less accurate. The Code section builds a 100×100100 \times 100 matrix with nearly dependent columns, whose condition number, defined in the conditioning note, is 101210^{12}, and solves Ax=bAx = b both ways. With numpy.linalg.solve the relative residual ∥b−Ax^∥/(∥A∥ ∥x^∥)\lVert b - A\hat x\rVert / (\lVert A\rVert\, \lVert \hat x\rVert) is about 10−1610^{-16}, at the level of rounding. Through the computed inverse it is 7⋅10−77 \cdot 10^{-7}, and the error in x^\hat x grows from 8⋅10−68 \cdot 10^{-6} to 9⋅10−59 \cdot 10^{-5}. A solver with a small residual has solved a nearby system exactly; the inverse gives no such guarantee.

And the inverse destroys structure. The 5×55 \times 5 matrix with 22 on the diagonal and −1-1 next to it has 13 nonzero entries, and its LU factors keep that band, because each elimination step subtracts the pivot row, with two nonzeros, from the one row below it. Its inverse has all 25 entries nonzero; its first row is 16(5,4,3,2,1)\tfrac16 (5, 4, 3, 2, 1). For a million unknowns the band has three million entries and the inverse 101210^{12}.

One identity about inverses is worth knowing because it saves work. Suppose AA is n×nn \times n and easy to solve with, diagonal or already factored, and it changes by a low-rank term UCVUCV, with UU of size n×kn \times k, an invertible CC of size k×kk \times k and VV of size k×nk \times n. The Sherman–Morrison–Woodbury formula, or matrix inversion lemma, gives the new inverse through a k×kk \times k system:

(A+UCV)−1=A−1−A−1U(C−1+VA−1U)−1VA−1.(A + UCV)^{-1} = A^{-1} - A^{-1}U\big(C^{-1} + VA^{-1}U\big)^{-1}VA^{-1} .

It holds whenever AA, CC and S=C−1+VA−1US = C^{-1} + VA^{-1}U are invertible. Multiplying the right side by A+UCVA + UCV gives II, and a one-sided inverse of a square matrix is the inverse. Boyd and Vandenberghe derive it instead by writing (A+UCV)x=b(A + UCV)x = b as a block system in xx and y=CVxy = CVx and eliminating xx.

Derivation: the product is the identity

Expand the product, collect the terms that end in S−1VA−1S^{-1}VA^{-1}, and use I+CVA−1U=C SI + CVA^{-1}U = C\,S:

(A+UCV)(A−1−A−1US−1VA−1)=I+UCVA−1−U(I+CVA−1U)S−1VA−1=I+UCVA−1−UC S S−1VA−1=I.\begin{aligned} &(A + UCV)\big(A^{-1} - A^{-1}U S^{-1} V A^{-1}\big) \\ &= I + UCVA^{-1} - U\big(I + CVA^{-1}U\big) S^{-1} VA^{-1} \\ &= I + UCVA^{-1} - UC\, S\, S^{-1} VA^{-1} \\ &= I . \end{aligned}

For a diagonal AA the formula needs A−1UA^{-1}U (nknk operations), VA−1UVA^{-1}U (nk2nk^2) and one k×kk \times k solve (k3k^3). With n=2000n = 2000 and k=5k = 5 it solves the system in O(nk2)O(nk^2) operations instead of O(n3)O(n^3), and k=1k = 1 is the Sherman–Morrison update after a rank-one change. The Bayes course uses the formula to move between two sizes: Bayesian linear regression inverts a d×dd \times d matrix built from dd features, a Gaussian process an N×NN \times N matrix over NN data points, and the formula turns one inverse into the other, so the computation can be done in the smaller space.

When there is no exact solution: least squares#

Data rarely satisfy a tall system exactly. With a1=(1,0,1)a_1 = (1, 0, 1), a2=(0,1,1)a_2 = (0, 1, 1) and b=(1,2,6)b = (1, 2, 6), the left null space of A=[a1 a2]A = [a_1\ a_2] is spanned by y=(1,1,−1)y = (1, 1, -1), and y⊤b=−3≠0y^\top b = -3 \ne 0: no xx gives Ax=bAx = b. The useful question becomes which xx makes AxAx closest to bb. Minimizing ∥Ax−b∥2\lVert Ax - b\rVert^2 leads to the normal equations A⊤A x^=A⊤bA^\top A\, \hat x = A^\top b, a square system that elimination solves; here they give x^=(2,3)\hat x = (2, 3).

Their derivation by calculus and their statistics are in the least-squares note of the Machine Learning course, and their geometry, with this same example, in the next note. Forming A⊤AA^\top A is itself a numerical risk, and the next note solves the problem through the QR factorization instead.

Where machine learning solves linear systems#

Least squares and ridge regression solve (X⊤X+λI) w=X⊤y(X^\top X + \lambda I)\, w = X^\top y, a symmetric system usually handled by the Cholesky factorization, the variant of LU for symmetric positive definite matrices (ridge). The density of a multivariate Gaussian contains (x−μ)⊤Σ−1(x−μ)(x - \mu)^\top \Sigma^{-1} (x - \mu), and a Gaussian process prediction contains K−1yK^{-1} y; both are computed by solving with a factored matrix. Each step of Newton’s method solves Hd=−gHd = -g with the Hessian HH and the gradient gg (unconstrained optimization). Glow learns its invertible 1×11 \times 1 convolutions directly in the factored form W=PLUW = PLU, so that the inverse and the determinant cost little (invertible convolutions).

Where it breaks#

Dense elimination stops being an option long before the matrices of practice run out. For n=105n = 10^5 unknowns, the matrix alone takes 8n28n^2 bytes, 80 GB in double precision, and the factorization n3/3≈3⋅1014n^3/3 \approx 3 \cdot 10^{14} multiply–adds.

Large matrices are usually sparse, and elimination can destroy the sparsity. Take the 1000×10001000 \times 1000 arrow matrix: the diagonal, plus a full first row and first column, 2,998 nonzeros in all. Eliminating the first unknown first subtracts a multiple of the full first row from every other row, and the factor fills in completely. Its Cholesky factor has 500,500 nonzeros, the whole lower triangle. Number the unknowns in reverse order, so that the full row and column come last, and the same matrix has a factor with 1,999 nonzeros. The order of elimination decides the cost (Boyd and Vandenberghe, 2004, appendix C). Sparse solvers choose the order by heuristics, and the largest systems are solved by iterative methods, which only multiply by the matrix.

Exactness is the other limit. With measured data, a dependent set of columns becomes independent after the smallest perturbation, so “is bb in the column space?” needs a tolerance; the SVD note gives the numerical rank. And for an ill-conditioned matrix even the best solver returns an x^\hat x that solves a nearby system exactly but may be far from the true xx; the conditioning note measures the gap.

What you should remember#

  • Ax=bAx = b reads three ways: an intersection of hyperplanes, a combination of columns equal to bb, and a point in the image of a map.
  • Elimination is the factorization A=LUA = LU, or PA=LUPA = LU with row exchanges: n3/3n^3/3 multiply–adds once, then n2n^2 per right-hand side.
  • Partial pivoting takes the largest pivot in the column and keeps every multiplier at most 1.
  • The row and column spaces have dimension rr, the kernel n−rn - r, the left null space m−rm - r.
  • A solution exists exactly when y⊤b=0y^\top b = 0 for all y∈ker⁡A⊤y \in \ker A^\top; all solutions are xp+ker⁡Ax_p + \ker A.
  • Write A−1bA^{-1}b, compute with the factors; Woodbury inverts a low-rank change through a k×kk \times k system.

Code#

The examples of the note: elimination by hand with the multipliers kept, the library LU with pivoting, the cost count, the four subspaces, the solvability test, a small pivot, solving with and without the inverse, the Woodbury formula and the arrow matrix. Seeds are fixed; exact numbers can differ slightly across platforms and library versions, especially in the inverse experiment. The script runs in about a second.

import numpy as np
from scipy.linalg import lu, lu_factor, lu_solve, null_space, solve_triangular

rng = np.random.default_rng(0)
rank = np.linalg.matrix_rank

# the 2 x 2 system: row picture and column picture give the same x
M = np.array([[2., -1], [1, 1]]); bm = np.array([1., 5])
xm = np.linalg.solve(M, bm)
print(xm, xm[0] * M[:, 0] + xm[1] * M[:, 1])     # [2. 3.] [1. 5.]

# Gaussian elimination without row exchanges, keeping the multipliers
def lu_nopivot(A):
    U = A.astype(float).copy(); n = len(U); L = np.eye(n)
    for k in range(n - 1):
        for i in range(k + 1, n):
            L[i, k] = U[i, k] / U[k, k]          # the multiplier
            U[i, k:] -= L[i, k] * U[k, k:]       # row i minus multiplier times the pivot row
    return L, U

A = np.array([[2., 1, -1], [4, 5, -3], [-2, 5, -2]]); b = np.array([1., 5, 2])
L, U = lu_nopivot(A)
print(L.tolist(), U.tolist(), np.allclose(L @ U, A))
# [[1.0, 0.0, 0.0], [2.0, 1.0, 0.0], [-1.0, 2.0, 1.0]] [[2.0, 1.0, -1.0], [0.0, 3.0, -1.0], [0.0, 0.0, -1.0]] True
c = solve_triangular(L, b, lower=True)           # forward substitution: Lc = b
x = solve_triangular(U, c)                       # back substitution: Ux = c
print(c, x)                                      # [ 1.  3. -3.] [1. 2. 3.]

# library LU uses partial pivoting: PA = LU with the largest available pivot; same solution
P, Lp, Up = lu(A)                                # scipy returns A = P Lp Up
print(np.allclose(P @ Lp @ Up, A), Up[0, 0], np.abs(Lp).max(), lu_solve(lu_factor(A), b))
# True 4.0 1.0 [1. 2. 3.]

# a tiny pivot: without row exchanges the answer is wrong, with partial pivoting it is right
As = np.array([[1e-17, 1], [1, 1]]); bs = np.array([1., 2])
Ls, Us = lu_nopivot(As)
print(solve_triangular(Us, solve_triangular(Ls, bs, lower=True)), np.linalg.solve(As, bs))   # [0. 1.] [1. 1.]

# multiply-adds of elimination on an n x n matrix: sum of (n - k)^2, about n^3 / 3
for n in (3, 10, 100, 1000):
    print(n, sum((n - k) ** 2 for k in range(1, n)), round(n ** 3 / 3))
# 3 5 9 | 10 285 333 | 100 328350 333333 | 1000 332833500 333333333

# the four subspaces of a 3 x 4 matrix of rank 2
A4 = np.array([[1., 2, 0, 1], [2, 4, 1, 4], [3, 6, 1, 5]])
print(rank(A4), null_space(A4).shape[1], null_space(A4.T).shape[1])   # 2 2 1: dimensions r, n - r, m - r
for v in ([-2, 1, 0, 0], [-1, 0, -2, 1]):
    print(A4 @ v)                                # [0. 0. 0.] twice: a basis of the kernel
print(np.array([1, 1, -1]) @ A4)                 # [0. 0. 0. 0.]: the left null space
# solvable exactly when b is in the column space, i.e. b1 + b2 - b3 = 0
for bb in ([1., 3, 4], [1., 3, 5]):
    print(bb, rank(np.column_stack([A4, bb])), np.array([1, 1, -1]) @ bb)
# [1.0, 3, 4] 2 0.0 | [1.0, 3, 5] 3 -1.0
xp = np.array([1., 0, 1, 0])
print(A4 @ xp, A4 @ (xp + 2 * np.array([-2, 1, 0, 0]) - np.array([-1, 0, -2, 1])))   # [1. 3. 4.] [1. 3. 4.]

# the inverse of a 2 x 2 matrix, and the inverse of a sparse matrix is dense
print(np.linalg.inv(M) * 3, np.linalg.inv(M) @ bm)    # [[ 1.  1.] [-1.  2.]] [2. 3.]
T = 2 * np.eye(5) - np.eye(5, k=1) - np.eye(5, k=-1)
Lt, Ut = lu_nopivot(T)
print(np.count_nonzero(T), np.count_nonzero(np.abs(Lt) + np.abs(Ut) > 1e-12),
      np.count_nonzero(np.abs(np.linalg.inv(T)) > 1e-12), (6 * np.linalg.inv(T)).round(6)[0])
# 13 13 25 [5. 4. 3. 2. 1.]: the factors keep the band (L and U together), the inverse fills in

# solving through the inverse: a much larger residual (n = 100, condition number 1e12)
n = 100
Q1, _ = np.linalg.qr(rng.normal(size=(n, n))); Q2, _ = np.linalg.qr(rng.normal(size=(n, n)))
Ak = Q1 @ np.diag(np.logspace(0, -12, n)) @ Q2.T
xt = rng.normal(size=n); bk = Ak @ xt
for name, xh in (('solve', np.linalg.solve(Ak, bk)), ('inv', np.linalg.inv(Ak) @ bk)):
    print(name, f'{np.linalg.norm(bk - Ak @ xh) / (np.linalg.norm(Ak, 2) * np.linalg.norm(xh)):.0e}',
          f'{np.linalg.norm(xh - xt) / np.linalg.norm(xt):.0e}')
# solve 1e-16 8e-06 | inv 7e-07 9e-05   (relative residual, relative error)

# Sherman-Morrison-Woodbury: diagonal plus rank 5, n = 2000, solved through a 5 x 5 system
n, k = 2000, 5
d = rng.uniform(1, 2, n); Uw = rng.normal(size=(n, k)); Cw = np.eye(k); bw = rng.normal(size=n)
Ab, AU = bw / d, Uw / d[:, None]                 # A^-1 b and A^-1 U for the diagonal A
xw = Ab - AU @ np.linalg.solve(np.linalg.inv(Cw) + Uw.T @ AU, Uw.T @ Ab)
print(np.allclose(xw, np.linalg.solve(np.diag(d) + Uw @ Cw @ Uw.T, bw)))   # True

# the arrow matrix: eliminating the full row first fills the factor in; reversing the order does not
n = 1000
Ar = n * np.eye(n); Ar[0, :] = 1; Ar[:, 0] = 1; Ar[0, 0] = n
nnz = lambda F: np.count_nonzero(np.abs(F) > 1e-14)
print(nnz(Ar), nnz(np.linalg.cholesky(Ar)), nnz(np.linalg.cholesky(Ar[::-1, ::-1])))   # 2998 500500 1999

# no exact solution: b = (1, 2, 6) is not a combination of (1, 0, 1) and (0, 1, 1)
A2 = np.column_stack([[1., 0, 1], [0, 1, 1]]); b2 = np.array([1., 2, 6])
print(rank(A2), rank(np.column_stack([A2, b2])), np.array([1, 1, -1]) @ b2, np.linalg.lstsq(A2, b2, rcond=None)[0])
# 2 3 -3.0 [2. 3.]

Next#

Least squares replaced “solve Ax=bAx = b” by “make AxAx as close to bb as possible”, and “close” has not been defined yet: a vector space has no lengths and no angles. The next note adds them through the inner product, finds the closest point of a subspace by orthogonal projection, and builds the QR factorization, which solves least squares without forming A⊤AA^\top A.

References#

  • G. Strang. Introduction to Linear Algebra, 5th ed. Wellesley-Cambridge Press, 2016. Section 1.3 (the column and row pictures), section 2.5 (inverse matrices), section 3.5 (dimensions of the four subspaces).
  • S. Boyd, L. Vandenberghe. Convex Optimization. Cambridge University Press, 2004. Appendix C (numerical linear algebra background), in the form of the EE364a lecture Numerical linear algebra background: flop counts, the factor–solve method, sparse Cholesky and the arrow matrix, block elimination and the matrix inversion lemma.
  • L. N. Trefethen, D. Bau III. Numerical Linear Algebra. SIAM, 1997. Lecture 21 (pivoting, and why the row exchanges collect into PA=LUPA = LU), Lecture 22 (stability of Gaussian elimination and the growth bound 2n−12^{n-1}).
  • I. Oseledets. Numerical Linear Algebra, course notebooks, 2024. Lecture 5 (linear systems: Gaussian elimination, LU, pivoting and element growth, the condition number).