Matrix Operations

The same recipe matrix, a new right-hand side every day. Eliminate from scratch each day and 100 days of a 1,000 × 1,000 system cost 3.3 × 1010 steps. Factor once into L and U and they cost 4.3 × 108: 77 times less.

Press Next day, then switch the method and the size. Then we build, piece by piece, triangular solves, LU, pivoting, inverses, Cholesky, least squares and the condition number.

You need a little Python and matrix times vector. We build the rest from zero.

Based on Chapter 28, Matrix Operations, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Multithreaded Algorithms. Next: Linear Programming.

Solve a new day

30

The 3 × 3 system is the page's running example. Step counts are the leading terms: n3/3 to eliminate or factor, n2 for the two triangular solves.

Chapter 0

One Matrix, Many Right-Hand Sides

Write a daily production plan as Ax = b, and see which part of the work repeats

A factory makes three chemicals from three raw materials. The recipes never change. Every morning a truck brings a new load of materials. You must decide how many liters of each chemical to make, so that nothing is left over.

Call the liters x1, x2, x3 and the delivered kilograms b1, b2, b3. Each material gives one equation. The matrix A holds the recipes: row i, column j is the kilograms of material i that one liter of chemical j uses. The plan is a system of linear equations, Ax = b.

Find where two equations agree

Each equation in two unknowns is a line. The answer is the crossing. Drag the knobs until the lines are parallel.

3.0
10

Line 1 is 2x1 + x2 = 5. Line 2 is x1 + a22x2 = b2.

Parallel lines have no crossing, or a whole line of them. The matrix is then singular: no unique answer exists. A matrix with a unique answer for every b is nonsingular.

Gaussian elimination solves Ax = b by subtracting multiples of rows until the system is triangular. For n equations it costs about n3/3 multiply-add steps. That work depends only on A. Tomorrow, with a new b, plain elimination does all of it again.

Worked number: n = 1,000 and 100 deliveries. Eliminating each day costs 100 × (3.3 × 108 + 106) = 3.3 × 1010 steps. Factoring A once costs 3.3 × 108, and each day then costs 106: 4.3 × 108 in total, 77 times less.

The failure. Symptom: a solver call takes the same long time for every new b. Measure: time two calls; if both scale like n3, the solver factors A each time. Fix: factor once and keep the factors (in SciPy, lu_factor once, then lu_solve per b).

The road

  1. Triangular systems: why a triangle solves in n2 steps.
  2. LU decomposition: elimination that keeps its multipliers. The hero's L and U.
  3. Pivoting: swap rows so you never divide by a small number.
  4. Inverse and determinant: both fall out of the factors.
  5. Multiply equals invert: the two problems cost the same.
  6. Cholesky: half the work when A is symmetric positive-definite.
  7. Least squares: the best answer when no exact one exists (the showcase).
  8. Conditioning: how many digits of the answer you can trust.
  9. The field guide: terms, numbers, code and the credit.
You solve Ax = b for 100 different b, with the same n × n matrix A. Which plan does the least work?

Chapter 1

Triangular Systems Solve in n2 Steps

Peel off one unknown per row, top down or bottom up

A lower-triangular matrix has only zeros above its diagonal. Its first row holds one unknown, so you read it off. The second row then holds one new unknown, and so on down. A unit lower-triangular matrix also has 1s on its diagonal.

Take the unit lower-triangular matrix L from this page's example and a right-hand side b. Call the unknown vector y, and the entry of L in row i, column j, lij.

Say it aloud

y-i equals b-i minus the sum over j less than i of l-i-j times y-j.

yi
y-i the unknown of row i, found now.
bi
b-i the right-hand side of row i.
Σj<i
the sum over j less than i one term for each column left of the diagonal.
lij
l-i-j the entry of L in row i, column j.
yj
y-j an unknown from an earlier row, already known.
In plain words

Go down the rows. In row i, multiply each known y-j by its l-i-j, add those up, and subtract the total from b-i. What is left is y-i.

With numbers

L has rows (1, 0, 0), (2, 1, 0), (3, 9, 1) and b = (6, 16, 46). Then y1 = 6, y2 = 16 − 2 × 6 = 4, and y3 = 46 − 3 × 6 − 9 × 4 = −8.

Peel one unknown per row

Pick forward (L, top down) or back (U, bottom up). Press Step. The row in use lights up, and its known values feed the new one.

The page's example. Warm entries are multipliers in L; purple entries are U.

An upper-triangular matrix U has zeros below its diagonal. Back substitution runs the same idea from the bottom row up. It divides by the diagonal entry uii, because U has no 1s there:

xi = (yi − Σj>i uij xj) / uii. Take U rows (2, 3, 1), (0, 1, 3), (0, 0, −8) and y = (6, 4, −8). Then x3 = −8 / −8 = 1, x2 = 4 − 3 = 1, x1 = (6 − 3 − 1) / 2 = 1.

Count the work. Row i uses i − 1 multiply-adds, so one triangle costs 0 + 1 + … + (n − 1) = n(n − 1)/2. Both triangles together cost about n2. For n = 1,000 that is 106 steps, against 3.3 × 108 to eliminate.

The failure. Symptom: back substitution returns inf or nan. Measure: print the diagonal of U and look for a 0. Fix: A is singular, or the factoring needed a row swap (Chapter 3).

Why can forward substitution find y3 in one step?

Chapter 2

LU Decomposition: Elimination With a Memory

Keep every multiplier, and the elimination becomes two reusable triangles

Elimination zeroes the entries below each pivot, the diagonal entry of the column you clear. To clear row i in column k, it subtracts a multiplier times row k. The multiplier is the entry to clear divided by the pivot. Call it lik = aik / akk.

Then every entry aij to the right in row i changes:

Say it aloud

a-i-j becomes a-i-j minus l-i-k times a-k-j.

aij
a-i-j the entry in row i, column j, after the update.
←
becomes overwrite the old value in place.
aij
a-i-j the same entry before the update.
lik
l-i-k the multiplier for row i at column k: a-i-k over the pivot a-k-k.
akj
a-k-j the pivot row's entry in the same column j.
In plain words

For each column k, and each row i below the pivot: compute l-i-k, then subtract l-i-k times the pivot row from row i. Write l-i-k into L. What stays in the matrix becomes U.

With numbers

A has rows (2, 3, 1), (4, 7, 5), (6, 18, 22). Column 1: l31 = 6 / 2 = 3, so a32 = 18 − 3 × 3 = 9 and a33 = 22 − 3 × 1 = 19. Column 2: l32 = 9 / 1 = 9, so a33 = 19 − 9 × 3 = −8.

Clear one entry, keep its multiplier

Press Step. One entry below a pivot turns to 0, and its multiplier moves into L. Then try the matrix whose first pivot is 0.

The multipliers 2, 3 and 9 fill L below its 1s. The pivots 2, 1 and −8 sit on U's diagonal.

The result is the LU decomposition A = LU. Here L has rows (1, 0, 0), (2, 1, 0), (3, 9, 1). U has rows (2, 3, 1), (0, 1, 3), (0, 0, −8). Check row 3: 3 × (2, 3, 1) + 9 × (0, 1, 3) + (0, 0, −8) = (6, 18, 22).

To solve Ax = b, write LUx = b. Solve Ly = b, then Ux = y: the two triangles of Chapter 1. With b = (6, 16, 46) you get y = (6, 4, −8) and x = (1, 1, 1). The factoring costs about n3/3; it is the elimination itself. L and U also fit in A's own n2 cells: L's multipliers go below the diagonal, and its 1s need no storage.

The failure. Symptom: a division by zero in the first column. Measure: look at the pivot akk before you divide. Fix: swap in a row with a nonzero entry; that is pivoting, next.

During elimination, row 3 had 6 in column 1 and the pivot was 2. What goes into L, and where?

Chapter 3

Pivoting: Never Divide by a Small Number

Swap the biggest entry to the pivot, and every multiplier stays at 1 or less

A zero pivot stops elimination. A tiny pivot is worse: it does not stop, it quietly ruins the answer. Take these two equations, with ε = 0.0001:

ε x1 + x2 = 1 and x1 + x2 = 2. The true answer is x1 = 1.0001, x2 = 0.9999.

Suppose the computer keeps 3 significant digits. The multiplier is 1 / 0.0001 = 10,000. Row 2 becomes (1 − 10,000) x2 = 2 − 10,000, and both sides round to −1.00 × 104. So x2 = 1.00, and row 1 gives x1 = (1 − 1.00) / 0.0001 = 0. That is 100% wrong.

Break it with a small pivot

Shrink ε and the digits the computer keeps. Then turn on pivoting, which swaps the rows first.

−4

Every operation rounds to the chosen number of significant digits. The double setting does not round.

Partial pivoting fixes this. Before clearing column k, find the entry with the largest absolute value at or below the diagonal, and swap its row up. Record the swaps in a permutation matrix P: the identity matrix with its rows reordered.

Say it aloud

P A equals L U.

P
P the permutation: it puts the rows of A in the order the swaps chose.
A
A the original matrix.
L
L unit lower-triangular; every multiplier has size 1 or less.
U
U upper-triangular, with the chosen pivots on its diagonal.
In plain words

Reorder the rows of A by P, then factor as before. To solve Ax = b, reorder b the same way: solve Ly = Pb, then Ux = y. CLRS calls this the LUP decomposition.

With numbers

B has rows (1, 2, 3), (4, 5, 6), (7, 8, 0). Column 1 picks 7, column 2 picks 6/7 ≈ 0.857. PB has rows (7, 8, 0), (1, 2, 3), (4, 5, 6). L's multipliers are 1/7, 4/7 and 1/2, all at most 1. U's diagonal is 7, 0.857, 4.5.

Why it works: the largest entry is the pivot, so every multiplier has size at most 1. Small multipliers keep rounding errors from being blown up. The cost is about n2/2 comparisons, nothing next to n3/3. In the worst case U's entries can still grow by a factor of 2n−1, but such matrices are rare in practice.

The failure. Symptom: a solver gives answers far off on some inputs and fine on others. Measure: compute the residual b − Ax; with no pivoting it can be large. Fix: always pivot. LAPACK's general solver, used by numpy.linalg.solve, does.

Why does partial pivoting pick the entry with the largest absolute value in the column?

Chapter 4

Inverse and Determinant From the Factors

Solve for one column of the inverse at a time, and read the determinant off U

The inverse A−1 is the matrix with A A−1 = I, the identity. Look at column j of that equation. A times column j of A−1 equals ej, the column of I with a 1 in place j. So the inverse is n systems with one A. Factor once, then do n pairs of triangular solves.

Build the inverse column by column

Press Next column. Each press solves L y = ej and U x = y with the factors from Chapter 2.

The page's example A. The last line multiplies U's diagonal.

The cost is n3/3 to factor plus n × n2 for the solves: about n3 in all. To get one answer x, the inverse route also multiplies A−1b. At n = 1,000 that is 1.3 × 109 steps against 3.3 × 108 for one LU solve: four times the work. It also tends to lose more digits to rounding. Solve; do not invert.

The determinant comes for free. The determinant of a triangular matrix is the product of its diagonal. det(L) = 1. Each row swap flips the sign. Call the number of swaps s.

Say it aloud

det of A equals minus one to the s, times u-one-one times u-two-two, and so on up to u-n-n.

det(A)
det of A the determinant: the factor by which A scales volume. It is 0 exactly when A is singular.
(−1)s
minus one to the s plus 1 for an even number of swaps s, minus 1 for an odd number.
u11 ··· unn
u-one-one up to u-n-n the pivots on U's diagonal, multiplied together.
In plain words

Factor PA = LU. Multiply the pivots on U's diagonal. Flip the sign if the number of swaps s is odd.

With numbers

For A, s = 0 and the pivots are 2, 1, −8: det(A) = 2 × 1 × (−8) = −16. For B of Chapter 3, s = 2 and the pivots are 7, 6/7, 4.5: det(B) = 7 × 6/7 × 4.5 = 27.

The textbook cofactor expansion has n! terms; at n = 20 that is 2.4 × 1018. LU gives the determinant in n3/3 steps.

The failure. Symptom: A−1 has huge entries and A A−1 is visibly not I. Measure: compute the largest entry of A A−1 − I. Fix: A is close to singular (Chapter 8); solve the system you need instead of inverting.

You factored PA = LU with 3 row swaps, and U's diagonal is 2, 5, −1. What is det(A)?

Chapter 5

Multiplying Is as Hard as Inverting

Hide a product inside an inverse, and an inverse inside products

Multiplying two n × n matrices by the school method costs n3. Strassen's method (CLRS Chapter 4) costs about n2.81. CLRS proves that inversion costs the same as multiplication, up to a constant factor. A faster multiply gives a faster inverse, and the other way round.

The first direction is a trick. Build a 3n × 3n matrix M from the identity I and the two matrices A and B. Invert M. The product AB appears in the top-right block.

Read a product out of an inverse

Each entry stands for an n × n block; here n = 1, so A and B are numbers. Drag them and watch the corner of M−1.

2
3

With real blocks, the same picture holds: 0 and I are n × n blocks of zeros and the identity.

M = [I A 0; 0 I B; 0 0 I] has inverse [I −A AB; 0 I −B; 0 0 I]. With A = 2 and B = 3, the corner is 6.

So if you can invert a 3n matrix in time I(3n), you can multiply in that time. The other direction (CLRS Theorem 28.2) splits the matrix into four blocks and inverts recursively. Each level needs a few multiplications, so inversion costs a constant times the cost of multiplying. LUP decomposition reduces to multiplication the same way (Bunch and Hopcroft, 1974).

Call the true exponent of matrix multiplication ω: the smallest power with an nω method. Reading the input already takes n2, so ω is at least 2. Research has pushed the upper bound below 2.372. Nobody knows if ω = 2. Real libraries still use blocked n3 methods, because their constants are small and they use the cache well.

The failure. Symptom: a recursive block inverse breaks when n is odd. Measure: check whether n is a power of 2. Fix: pad A with an identity block up to the next power of 2, as CLRS does. That at most doubles n, a constant factor.

Someone finds an n2.2 matrix multiplication. What follows for matrix inversion?

Chapter 6

Symmetric Positive-Definite Matrices and Cholesky

Use symmetry to factor with half the work and no row swaps

A matrix is symmetric when A equals its transpose: entry (i, j) equals entry (j, i). It is positive-definite when xTAx > 0 for every nonzero vector x. Both together give a symmetric positive-definite (SPD) matrix. Covariance matrices are SPD when no variable is a mix of the others, and so is ATA when A's columns are independent.

CLRS shows that LU on an SPD matrix never meets a zero pivot, so it needs no swaps. Symmetry goes further: U is a scaled copy of LT. The Cholesky decomposition writes A = LLT, with L lower-triangular and a positive diagonal. Call L's entries lij and A's entries aij.

Say it aloud

l-j-j equals the square root of a-j-j minus the sum over k less than j of l-j-k squared.

ljj
l-j-j the diagonal entry of L in row j.
√
the square root of needs a positive number inside; for an SPD matrix it always gets one.
ajj
a-j-j the diagonal entry of A in row j.
Σk<j
the sum over k less than j one term for each column left of the diagonal.
ljk2
l-j-k squared an entry of row j of L, already computed, squared.
In plain words

Take the diagonal entry a-j-j. Subtract the squares of the entries already in row j of L. The square root of what is left is l-j-j. If what is left is 0 or negative, A is not SPD.

With numbers

A has rows (4, 2, 2), (2, 5, 3), (2, 3, 6). Row 3 of L starts with l31 = 1 and l32 = 1, so l33 = √(6 − 1 − 1) = √4 = 2.

Entries below the diagonal use the same pattern, divided by the diagonal of column j:

lij = (aij − Σk<j lik ljk) / ljj. Example: l32 = (3 − 1 × 1) / 2 = 1. Here L has rows (2, 0, 0), (1, 2, 0), (1, 1, 2).

Factor entry by entry, then break it

Press Step to fill L one entry at a time. Then lower the corner a33 until the square root has nothing left to take.

6

The last step takes the root of a33 − 2. At a33 = 2 or below, A is not positive-definite.

Cholesky computes only one triangle, so it costs about n3/6, half of LU. It needs no pivoting. It is also the cheapest test for SPD: try it, and see if a square root fails.

The failure. Symptom: numpy.linalg.cholesky raises LinAlgError on a covariance matrix. Measure: count samples against variables; fewer samples than variables makes the covariance singular. Fix: get more data, or add a small multiple of I to the diagonal.

Why does Cholesky cost about n3/6 while LU costs n3/3?

Chapter 7

Least Squares: The Best Wrong Answer

When no line passes through every point, find the one that misses least

Four measurements: (1, 2), (2, 3), (3, 6), (4, 8). You want a line y = c0 + c1t. Each point gives one equation, so you have 4 equations and 2 unknowns. No line passes through all four. We call such a system overdetermined.

Write it as Ax ≈ b. Row i of A is (1, ti), b holds the measured y values, and x = (c0, c1). The residual r = b − Ax is the miss at each point. Least squares picks the x that makes the sum of squared residuals smallest. Setting its derivative to 0 gives 2AT(Ax − b) = 0, and so:

Say it aloud

A-transpose A x equals A-transpose b.

AT
A-transpose A with rows and columns swapped: n × m.
A
A the m × n design matrix: one row per measurement, one column per unknown.
x
x the n coefficients you want, here c-zero and c-one.
AT
A-transpose the same transpose on the right side.
b
b the m measured values.
In plain words

Form the small n × n matrix A-transpose A and the vector A-transpose b. Solve that square system for x, with Cholesky when A's columns are independent. These are the normal equations.

With numbers

ATA has rows (4, 10), (10, 30). ATb = (19, 58), since 2 + 3 + 6 + 8 = 19 and 2 + 6 + 18 + 32 = 58. Solving gives c1 = 2.1 and c0 = −0.5: the line y = −0.5 + 2.1t.

The residuals are 0.4, −0.7, 0.2 and 0.1; their squares add to 0.7. They also sum to 0. That is ATr = 0 at work: the residual is normal, meaning perpendicular, to every column of A. The fit is the shadow of b on the space the columns span.

Fit the points you place

Tap the plot to add points. Drag the degree. Pink bars are residuals. Watch the condition number of ATA as the degree climbs.

1

The fit uses a QR solve for the curve. The condition number is of ATA for t from 0 to 10, the matrix the normal equations would factor. The noisy curve comes from a formula plus fixed noise, not from data.

A polynomial of degree d has d + 1 coefficients, so A gets columns 1, t, t2, …, td. The normal matrix stays (d + 1) × (d + 1), whatever the number of points. With 1,000 points and degree 3 it is 4 × 4. CLRS writes the answer as x = A+b, where A+ = (ATA)−1AT is the pseudoinverse. In code you still solve; you do not invert.

The failure. Symptom: a high-degree fit passes through every point and swings wildly between them. Measure: hold out a few points and compare their residuals with the training residuals. Fix: lower the degree, or get more points per coefficient.

You fit a degree-3 polynomial to 1,000 points with the normal equations. What size is ATA?

Chapter 8

Conditioning: How Many Digits Survive

Measure how much a small change in b can move x, and keep the normal equations from squaring it

Two lines that cross at a steep angle pin down the answer. Two lines that are nearly parallel do not: nudge one a little, and the crossing slides far along them. No algorithm can fix that. It is a property of the problem.

Nudge a nearly parallel pair

Bring the lines closer to parallel. Then nudge b2. The pink arrow shows how far the answer moves.

−2
0.005

The system is x1 + x2 = 2 and x1 + (1 + δ)x2 = 2 + δ + nudge. Without the nudge the answer is (1, 1).

Call the length of a vector its norm, written with double bars. A stretches some directions most and some least; the ratio of the largest stretch to the smallest is the condition number κ(A). Call the nudge to b δb, and the move it causes in x δx.

Say it aloud

The norm of delta-x over the norm of x is at most kappa of A times the norm of delta-b over the norm of b.

‖δx‖ / ‖x‖
norm of delta-x over norm of x the relative change in the answer.
≤
is at most a worst case; some nudges do less.
κ(A)
kappa of A the condition number: largest stretch over smallest stretch. It is at least 1.
‖δb‖ / ‖b‖
norm of delta-b over norm of b the relative change in the input.
In plain words

Take the relative error in b. Multiply it by kappa of A. The relative error in x is at most that. With about 16 digits in a double, expect to lose about the log, base 10, of kappa.

With numbers

A has rows (1, 1), (1, 1.0001), so κ(A) ≈ 40,000. With b = (2, 2.0001), x = (1, 1). Change b2 to 2.0002, a relative change of 3.5 × 10−5. Now x = (0, 2): a relative change of 1, under the bound 40,000 × 3.5 × 10−5 = 1.41.

Now the trap. The normal equations factor ATA, and its condition number is the square:

κ(ATA) = κ(A)2. For the A above: 40,0002 = 1.6 × 109, so about 9 of 16 digits are lost instead of about 5.

Three fixes, in order of cost:

  1. QR: write A = QR, with Q's columns perpendicular and of length 1, and R upper-triangular. Solve Rx = QTb. This keeps κ(A). It costs about twice the normal equations when m is much larger than n.
  2. SVD, the singular value decomposition: slower again, and it handles columns that are exact copies. numpy.linalg.lstsq uses it.
  3. Ridge: solve (ATA + λI)x = ATb. Adding λ to every eigenvalue lowers κ, at the price of a small bias toward 0.

The failure. Symptom: regression coefficients swing when you drop one data point. Measure: numpy.linalg.cond(A); above about 108 the normal equations keep no digits. Fix: remove near-duplicate columns, scale the columns, and solve with QR or SVD.

A has κ(A) = 108. You solve least squares with the normal equations in double precision, about 16 digits. About how many digits of x can you trust?

Chapter 9

The Field Guide

Keep the choices, the numbers, the checks and the core code on one page

Factor once, solve many times. LUP handles any nonsingular square matrix in n3/3, then n2 per right-hand side. Cholesky halves that for SPD matrices. Least squares turns a tall system into a small square one, and the condition number says how many digits survive.

Which factorization

FactorizationNeedsLeading costUse it for
PA = LU (LUP)square, nonsingularn3/3general Ax = b, determinant, inverse
A = LLT (Cholesky)symmetric positive-definiten3/6covariances, normal equations, SPD test
A = QRm ≥ n, independent columnsabout 2× the normal equationsleast squares without squaring κ
SVDany matrixmore than QRrank-deficient least squares, κ, the pseudoinverse

Terms and numbers

TermMeaningNumber on this page
Forward substitutionsolve L y = b top downy = (6, 4, −8)
Back substitutionsolve U x = y bottom upx = (1, 1, 1)
Multiplier likaik / akk, stored in L2, 3, 9
Pivotdiagonal entry you divide by2, 1, −8
Partial pivotingswap the largest entry up; |lik| ≤ 1ε = 0.0001, 3 digits: x1 = 0 without it
Determinant(−1)s times the pivotsdet(A) = −16
Inversen solves with columns of Icolumn 1 = (−4, 3.625, −1.875)
ωexponent of matrix multiplication2 ≤ ω < 2.372
CholeskyA = LLTL diagonal 2, 2, 2
Normal equationsATAx = ATby = −0.5 + 2.1t, squared residuals 0.7
Condition numberlargest over smallest stretch40,000, squared to 1.6 × 109

Before you trust a linear solve

  1. Factor once; reuse the factors for every right-hand side.
  2. Pivot. Never write LU without row swaps for a general matrix.
  3. Do not form A−1 to get x. Solve.
  4. If A is SPD, use Cholesky; a failed square root means it is not SPD.
  5. Check the residual b − Ax and the condition number of A.
  6. For least squares with κ(A) above about 106, use QR or SVD, not the normal equations.

The core code

pythonimport numpy as np

def lup_decompose(A):
    """CLRS LUP-DECOMPOSITION: L and U packed in one array, plus the row order."""
    a = np.array(A, dtype=float)
    n = len(a)
    perm = list(range(n))
    for k in range(n):
        p = k + int(np.argmax(np.abs(a[k:, k])))      # largest entry in column k
        if a[p, k] == 0:
            raise ValueError("singular matrix")
        a[[k, p]] = a[[p, k]]                         # swap rows (the L part too)
        perm[k], perm[p] = perm[p], perm[k]
        a[k+1:, k] /= a[k, k]                         # multipliers l_ik, kept below the diagonal
        a[k+1:, k+1:] -= np.outer(a[k+1:, k], a[k, k+1:])   # a_ij -= l_ik * a_kj
    return a, perm

def lup_solve(lu, perm, b):
    n = len(lu)
    y = np.zeros(n)
    for i in range(n):                                # forward: L y = P b
        y[i] = b[perm[i]] - lu[i, :i] @ y[:i]
    x = np.zeros(n)
    for i in reversed(range(n)):                      # back: U x = y
        x[i] = (y[i] - lu[i, i+1:] @ x[i+1:]) / lu[i, i]
    return x

def cholesky(A):
    n = len(A)
    L = np.zeros((n, n))
    for j in range(n):
        r = A[j][j] - L[j, :j] @ L[j, :j]             # what is left under the root
        if r <= 0:
            raise ValueError("not positive definite")
        L[j, j] = np.sqrt(r)
        for i in range(j + 1, n):
            L[i, j] = (A[i][j] - L[i, :j] @ L[j, :j]) / L[j, j]
    return L

A = [[2, 3, 1], [4, 7, 5], [6, 18, 22]]
lu, perm = lup_decompose(A)
print(lup_solve(lu, perm, np.array([6., 16, 46])))   # [1. 1. 1.]
print(cholesky([[4, 2, 2], [2, 5, 3], [2, 3, 6]]))    # rows (2,0,0) (1,2,0) (1,1,2)
t = np.array([1., 2, 3, 4]); y = np.array([2., 3, 6, 8])
X = np.column_stack([np.ones(4), t])
print(np.linalg.lstsq(X, y, rcond=None)[0])           # [-0.5  2.1]

Where it sits

Keep going

The takeaway. Elimination is work you can keep. Store the multipliers in L, pivot so they stay small, and every new right-hand side costs n2, not n3.
You must solve 10,000 systems with the same 500 × 500 matrix. About how many steps does factor-once take?

Now press Present or Teach. Explain from memory why a triangle solves in n2 and what L stores. Then say why the pivot should be the largest entry, and why the normal equations lose digits. Then go back to the hero, set n = 1,000, and say why the LU line stays flat.

Source

T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 28, Matrix Operations (third edition numbering). The LUP method, the inversion theorems and the normal equations follow the book. Cholesky, QR, SVD and ridge are standard numerical linear algebra; see L. N. Trefethen and D. Bau, Numerical Linear Algebra. The example matrices, devices and step counts are our own.

CLRS Chapter 28 · Matrix Operations
Next: Linear Programming · Back to Gleams