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:
The second equation gives ; substituting it into the first, , so , and . 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 , which inputs satisfy ?
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 and substitution ends in the contradiction ; replace it by and it ends in , true for every point of the line . 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 with
and the unknown . Read by rows, each equation is a line in the plane of the unknowns, here and , and a solution is a point on both. In each equation is a hyperplane, a flat set of dimension , and the solutions are their intersection. For a nonzero row , the solutions of are the kernel of a map of rank 1, of dimension by rank–nullity, and those of are that kernel shifted by one solution, as the existence section shows.
Read by columns, is the combination of the columns and , and the question is which combination gives . The answer, , is the solution .
Read as a map, is linear, and the question is whether lies in its image and which inputs reach it. A solution exists exactly when is in the column space, and any two solutions differ by a vector of the kernel.
A 2 × 2 system: the row picture and the column picture
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 the diagonal entry is the pivot. For each row below it, the multiplier , computed from the current entries, times row is subtracted from row , which makes its entry in column zero.
Take three equations, written as the augmented matrix , which appends to as an extra column:
- In column 1 the pivot is . Row 2 has the multiplier , and row 2 minus twice row 1 is . Row 3 has , and row 3 plus row 1 is .
- In column 2 the pivot is now . Row 3 has , and row 3 minus twice row 2 is .
- 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:
The solution satisfies the three original equations: , and . The pivots , and were all nonzero, which is what made each step possible.
Gaussian elimination on a 3 × 3 system, and the LU factorization it produces
Elimination is a factorization: A = LU#
The multipliers were used once and seemingly thrown away. Kept, they give a factorization of . Collect the multipliers of step in the vector , with zeros in positions to . Subtracting times row from every row is multiplication on the left by
because is row of ; here is the identity and the -th standard basis vector. Adding the rows back undoes the step, : the product equals , and because has a zero in position . For three unknowns, elimination and its reversal read
Multiplying out the two brackets leaves a cross term , which vanishes because the first entry of is zero. The last bracket has in column 1 and in column 2 below a diagonal of ones. It is a lower triangular matrix , with the multiplier in row and column , and
where is the upper triangular matrix at the end of elimination. For any the same expansion of gives : every product of two or more of the terms contains a factor with , which is zero because has zeros in positions 1 to . In the example,
Row 3 of the product is , the third row of .
The factorization separates the matrix from the right-hand side. Solving becomes two triangular solves: first from the top down, by forward substitution, then from the bottom up. Here , then gives , and gives , the right-hand column that elimination produced. Once is factored, every new costs only the two triangular solves.
Row exchanges and pivoting#
Elimination needs a nonzero pivot. The system
has the solution , but its first pivot is zero. Exchanging the two equations fixes it. In general rows are exchanged whenever needed, and the factorization becomes , where the permutation matrix is the identity with its rows reordered. Every invertible matrix has such a factorization. A nonzero pivot can always be found: if at step every entry of column from row down were zero, the first columns of the current matrix would lie in the span of and so be dependent; some would give , hence , and would be singular. That the exchanges made along the way can be collected into one in front, with the multipliers reordered inside , is shown in Trefethen and Bau (1997), lecture 21.
A small pivot is nearly as bad as a zero one. Replace the above by . Without an exchange the multiplier is . Double precision keeps about 16 significant digits (floating point), so the entry rounds to , and so does the right-hand side . Back substitution then gives and , while the true solution is 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 instead of ; the factors change and the solution does not. The entries of can still grow. One step replaces an entry by , and with that is at most twice the largest entry in absolute value, so steps grow the entries by a factor of at most . 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 changes only the block below and to the right of the pivot: rows, each with entries, at one multiply–add per entry. The entries of column become zero by construction and are not computed. Summing over the steps, with ,
multiply–adds for the LU factorization of an matrix. The divisions for the multipliers add only a lower-order term. Counting the multiplication and the addition as two floating-point operations gives the flops quoted by Boyd and Vandenberghe (2004, appendix C).
For the example the count is : four updated entries in step 1 and one in step 2. For it is , close to . Each triangular solve costs about multiply–adds, since row uses the unknowns already found and ; so with the factors at hand a new right-hand side costs : for , a million operations instead of a third of a billion.
Rank and the four fundamental subspaces#
Elimination works on any rectangular matrix . It produces an echelon form , in which each nonzero row starts with a pivot further right than the row above and zero rows come last. The rank is the number of pivots. Four subspaces belong to every :
- the column space , spanned by the columns: the image of ;
- the row space , spanned by the rows;
- the kernel (null space) ;
- the left null space , the combinations of rows that vanish, .
Their dimensions are all fixed by :
That the number of independent rows equals the number of independent columns is not obvious. A 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 , with invertible because every step can be undone. Then:
- Every row of is a combination of rows of and, since is invertible, the other way round, so . The nonzero rows of are independent, since each has its pivot in a column where the rows below it are zero. So .
- exactly when , so a combination of columns vanishes for exactly when the same combination vanishes for . In the 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 have zeros below row , so they lie in a space of dimension , of which the pivot columns are a basis; every other column is a combination of them. The same holds for the columns of in the same positions. So .
- Rank–nullity (previous note) gives , and, for , whose rank is , it gives .
Row 2 minus twice row 1, row 3 minus three times row 1, and then row 3 minus row 2 bring a matrix to echelon form:
There are two pivots, in columns 1 and 3, so . The pivot columns of , and , are a basis of : column 2 is twice column 1, and column 4 is column 1 plus twice column 3. The nonzero rows of , and , are a basis of .
The kernel has dimension . The non-pivot unknowns and are free, and gives and , so is spanned by and . The left null space has dimension . Elimination showed that row 3 minus row 1 minus row 2 is zero, so it is spanned by , and indeed .
The subspaces come in perpendicular pairs. Every row of has zero dot product with every kernel vector, since that is what says, and every column has zero dot product with every vector of the left null space. Here and . The next note makes “perpendicular” precise and uses these pairs for projections.
When a solution exists, and when it is unique#
When is reachable? The column picture gives the first answer and the left null space gives a test:
The test is necessary: if , then for every
It is also sufficient. Let have a basis of as its rows. The vectors with form a subspace of dimension , by rank–nullity. It contains , by the chain above, and also has dimension , so the two coincide.
Once one solution is known, the kernel describes all of them. If and , then , so the solutions are exactly the vectors with .
For the matrix above, is solvable exactly when . For the test passes, elimination gives , and with the particular solution is . All solutions are . For the test gives , and the last row of the eliminated system reads : no solution exists.
The rank decides which cases are possible:
| shape and rank | solutions of |
|---|---|
| (square, invertible) | exactly one, for every |
| (tall, independent columns) | none or exactly one |
| (wide, independent rows) | infinitely many, for every |
| and | none or infinitely many |
A solution exists for every exactly when , so that and the test is empty. It is unique whenever it exists exactly when , so that .
The inverse, and why it is rarely formed#
A square matrix with is invertible: there is a matrix with , and then . Why does it exist? By the table above, each system has exactly one solution; the matrix with these solutions as columns has . It is also a left inverse: , and since , every column of is zero. So a one-sided inverse of a square matrix is the inverse. Column of solves , so the inverse can be computed by solving systems with the same LU factors. Two rules follow from the definition. The inverse of a product reverses the order, , because . And , by transposing with the rule , which holds entry by entry, since .
For matrices there is a formula. Swapping the diagonal entries and negating the others gives a matrix whose product with is a multiple of ; the four entries of the product are , , and :
So, when ,
The number is the determinant, the subject of the next note but one. For the opening system , and
The formula 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 takes about multiply–adds, three times the LU factorization: for the factors, about for the forward solves , whose solutions begin with zeros, and for the back solves. Afterwards costs , the same as the two triangular solves. Nothing is saved.
It is also less accurate. The Code section builds a matrix with nearly dependent columns, whose condition number, defined in the conditioning note, is , and solves both ways. With numpy.linalg.solve the relative residual is about , at the level of rounding. Through the computed inverse it is , and the error in grows from to . A solver with a small residual has solved a nearby system exactly; the inverse gives no such guarantee.
And the inverse destroys structure. The matrix with on the diagonal and 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 . For a million unknowns the band has three million entries and the inverse .
One identity about inverses is worth knowing because it saves work. Suppose is and easy to solve with, diagonal or already factored, and it changes by a low-rank term , with of size , an invertible of size and of size . The Sherman–Morrison–Woodbury formula, or matrix inversion lemma, gives the new inverse through a system:
It holds whenever , and are invertible. Multiplying the right side by gives , and a one-sided inverse of a square matrix is the inverse. Boyd and Vandenberghe derive it instead by writing as a block system in and and eliminating .
Derivation: the product is the identity
Expand the product, collect the terms that end in , and use :
For a diagonal the formula needs ( operations), () and one solve (). With and it solves the system in operations instead of , and 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 matrix built from features, a Gaussian process an matrix over 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 , and , the left null space of is spanned by , and : no gives . The useful question becomes which makes closest to . Minimizing leads to the normal equations , a square system that elimination solves; here they give .
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 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 , 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 , and a Gaussian process prediction contains ; both are computed by solving with a factored matrix. Each step of Newton’s method solves with the Hessian and the gradient (unconstrained optimization). Glow learns its invertible convolutions directly in the factored form , 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 unknowns, the matrix alone takes bytes, 80 GB in double precision, and the factorization multiply–adds.
Large matrices are usually sparse, and elimination can destroy the sparsity. Take the 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 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 that solves a nearby system exactly but may be far from the true ; the conditioning note measures the gap.
What you should remember#
- reads three ways: an intersection of hyperplanes, a combination of columns equal to , and a point in the image of a map.
- Elimination is the factorization , or with row exchanges: multiply–adds once, then 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 , the kernel , the left null space .
- A solution exists exactly when for all ; all solutions are .
- Write , compute with the factors; Woodbury inverts a low-rank change through a 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 ” by “make as close to 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 .
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 ), Lecture 22 (stability of Gaussian elimination and the growth bound ).
- I. Oseledets. Numerical Linear Algebra, course notebooks, 2024. Lecture 5 (linear systems: Gaussian elimination, LU, pivoting and element growth, the condition number).