Matrices and Equations
local graph
So, matrices are not just tables of numbers but linear transformations; we have spent a lengthy chapter discovering this relationship.
Now, I want us to circle back to the good old tables of numbers once more, but representing systems of linear equations this time. Why? Simple. Because solving linear equations is the motivator behind key theoretical and technical innovations. In the previous chapter, we talked about inverse matrices but didn’t compute one in practice. With what we’re about to learn, we will be able to not only compute inverse matrices but do so blazing fast.
Let’s get to work!
Bookmark
5.1 Linear equations
Section titled “5.1 Linear equations”In practice, we can translate several problems into linear equations. For example, a cash dispenser has 20 and 20 bills than $50. The question is, how many of each bill does the machine have?
If we denote the number of 50 bills by x2, we obtain the equations

For two variables, as we have now, these are easily solvable by expressing one in terms of the other. Here, the first equation would imply x1 = 2x2. Plugging it back into the second equation, we obtain 90x2 = 900, which gives x2 = 10. Coming full circle, we can substitute this into x1 = 2x2, yielding the solutions

However, for thousands of variables like in real applications, we need a bit more craft. This is where linear algebra comes in. By introducing the matrix and vectors

the equation can be written in the form Ax = b. That is, in terms of linear transformations, we can reformulate the question: which vector x is mapped to b by the transformation A? This question is central in linear algebra, and we’ll dedicate this section to solving it.
5.1.1 Gaussian elimination
Section titled “5.1.1 Gaussian elimination”Let’s revisit our earlier example:

We can use the first equation x1 − 2x2 = 0 to get rid of the term x1 in the second equation 20x1 + 50x2 = 900. We can do this by multiplying it by 20 and subtracting it from the second row, obtaining 90x2 = 900, from which x2 = 10 is obtained. This can be substituted back into the first row, yielding x1 = 20.
What about the general case? Would this work for a general A ∈ℝn×n and x,b ∈ℝn? Absolutely. So far, we have used two rules for manipulating the equations in a linear system:
- Multiplying an equation with a nonzero scalar won’t change the solutions.
- Adding a scalar multiple of one row to another won’t change the solutions either.
Earlier, we applied these repeatedly to eliminate variables progressively in our simple example. We can easily do the same for n variables! First, let’s see what we are talking about!
Definition 21. (System of linear equations)
Let A ∈ ℝn×n be a matrix and b ∈ ℝn be a vector. The collection of equations

(5.1)
are called the system of linear equations determined by A and b.
A system of linear equations is often written in the short form Ax = b, where A is called its coefficient matrix. If the vector x satisfies Ax = b, it is called a solution.
Speaking of solutions, are there even any, and if so, how can we find them?
If a11 is nonzero, we can multiply the first equation of (5.1) by
and subtract it from the k-th equation.
This way, x1 will be eliminated from all but the first row, obtaining

(5.2)
To clear up this notation a bit, let’s denote the new coefficients with aij(1) and bi(1). So, we have

(5.3)
We can repeat the above process and use the second equation to get rid of the x2 variable in the third equation, and so forth.
This can be done n − 1 times in total, ultimately leading to an equation system A(n−1)x = b(n−1) where all coefficients below the diagonal of A(n−1) are 0:
.png)
(5.4)
Notice that the k-th elimination step only affects the coefficients from the (k + 1)-th row. Now we can work backward: the last equation ann(n−1)xn = bn(n−1) can be used to find xn. This can be substituted to the (n − 1)-th equation, yielding xn−1. Continuing like this, we can eventually find all x1,…,xn, obtaining a solution for our linear system.
This process is called Gaussian elimination, and it’s kind of a big deal. It is not only useful for solving linear equations, but it can also be used to calculate determinants, factor matrices into the product of simpler ones, and much more. We’ll talk about all of this in detail, but let’s focus on equations a little more.
Unfortunately, not all linear equations can be solved. For instance, consider the system

Subtracting the first equation from the second one yields

in the very first step, making it apparent that the equation has no solutions.
Before we turn to the technical details, let’s see a simple example of how Gaussian elimination is done in practice!
5.1.2 Gaussian elimination by hand
Section titled “5.1.2 Gaussian elimination by hand”To build a deeper understanding of Gaussian elimination, let’s consider the simple equation system

To keep track of our progress (and, since we are lazy, to avoid writing too much), we record the intermediate results as

with the coefficient matrix A on the left side and b on the other. To get a good grip on the method, I encourage you to follow along and do the calculations yourself by hand.
After eliminating the first variable from the second and third equations, we have

while the final step yields

From this form, we can unravel the solutions one by one.
In the 21st century, your chances of having to solve a linear equation by hand are close to 0. (If you are reading this book during the 22nd century or later, I am incredibly honored and surprised at the same time. Or, at least, I would be if I were still alive.) Still, understanding the general principles behind solving linear equations can take you very far.
5.1.3 When can we perform Gaussian elimination?
Section titled “5.1.3 When can we perform Gaussian elimination?”If you followed the description of Gaussian elimination carefully, you might have noticed that the process can break down. We might accidentally divide by 0 during any elimination step!
For instance, after the first step given by equation (5.2), the new coefficients are of the form

which is invalid if a11 = 0. In general, the k-th step involves division by akk(k−1). Since akk(k−1) is defined recursively, describing it in terms of A is not straightforward. For this, we introduce the concept of principal minors, the upper-left subdeterminants of a matrix.
Definition 22. (Principal minors)
Let
be an arbitrary square matrix. Define the submatrix
by omitting all rows and columns of
with indices larger than
. For instance,
![⌊ ⌋ [ ] ⌈a11 a12⌉ A1 = a11 , A2 = a a , 21 22](https://static.packt-cdn.com/products/9781837027873/graphics/media/file522.png)
and so on. The k-th principal minor of A, denoted by Mk, is defined by

The first and last principal minors are special, as M1 = a11 and Mn = detA. With principal minors, we can describe when Gaussian elimination is possible. In fact, it turns out that

and, in general, akk(k−1) =
.
To summarize, we can state the following.
Theorem 30.
Let
be an arbitrary square matrix, and let
be its
-th principal minor. If
for all
, then Gaussian elimination can be successfully performed.
As the proof is a bit involved, we are not going to do it here. (The difficult step is showing akk(k−1) = Mk∕Mk−1;’ the rest follows immediately.) The point is, if none of the principal minors are 0, the algorithm finishes.
We can simplify this requirement a bit and describe the Gaussian elimination in terms of the determinant, not the principal minors.
Theorem 31.
Let A ∈ℝn×n be an arbitrary square matrix. If detA≠0, then all principal minors are nonzero as well.
As a consequence, if the determinant is nonzero, the Gaussian elimination is successful. A simple and nice requirement.
5.1.4 The time complexity of Gaussian elimination
Section titled “5.1.4 The time complexity of Gaussian elimination”To get a handle on how fast the Gaussian elimination algorithm executes, let’s do a little complexity analysis. As described by (5.2), the first elimination step involves an addition and a multiplication for each element, except for those in the first row. That is 2n(n − 1) operations in total.
The next step is essentially the first step, done on the (n − 1) × (n − 1) matrix obtained from A(1) by removing its first row and column. This time, we have 2(n − 1)(n − 2) operations.
Following this train of thought, we quickly get that the total number of operations is

which doesn’t look that friendly. Since we are looking for the order of complexity instead of an exact number, we can be generous and suppose that at each elimination step, we are performing O(n2) operations. So, we have a time complexity of

meaning that we need around cn3 operations for Gaussian elimination, where c is an arbitrary positive constant. This might seem a lot, but in the beautiful domain of algorithms, this is good. O(n3) is polynomial time, and we can have much, much worse.
5.1.5 When can a system of linear equations be solved?
Section titled “5.1.5 When can a system of linear equations be solved?”So, we have just seen that for any linear equation

Gaussian elimination can be successfully performed if the principal minors M1,…,Mn−1 are nonzero. Notice one caveat about the result: Mn = detA can be zero as well. Turns out, this is quite an important detail.
If you have closely followed the discussion leading up to this point, you will see that we missed a crucial point: are there any solutions at all for a given linear equation? There are three options:
- There are no solutions.
- There is exactly one solution.
- There are multiple solutions.
All of these are relevant to us from a certain perspective, but let’s start with the most straightforward one: when do we have exactly one solution? The answer is simple: when A is invertible, the solution can be explicitly written as x = A−1b. Speaking in terms of linear transformations, we can find a unique vector x that is mapped to b. We summarize this idea in the following theorem.
Theorem 32.
Let
be an invertible matrix. Then, for any
, the equation
has a unique solution that can be written as
.
If A is invertible, then detA is nonzero. Thus, using what we have learned previously, Gaussian elimination can be performed, yielding the unique solution. Nice and simple.
If A is not invertible, the two remaining possibilities are in play: no vector is mapped to b, which means there are no solutions, or multiple vectors are mapped to b, giving infinite solutions.
Do you remember how we used the kernel of a linear transformation to describe its invertibility in Theorem 20? It turns out that kerA can also be used to find all solutions for a linear system.
Theorem 33.
Let A ∈ℝn×n be an arbitrary matrix and let x0 ∈ℝn be a solution to the linear equation Ax = b, where b ∈ℝn. Then, the set of all solutions can be written as

Proof. We have to show two things: (a) if x ∈x0 + kerA, then x is a solution; and (b) if x is a solution, then x ∈x0 + kerA.
(a) Suppose that x ∈ x0 + kerA, that is, x = x0 + y for some y ∈ kerA. Then,

which shows that x is indeed a solution.
(b) Now let x be an arbitrary solution. We have to show that x −x0 ∈ kerA. This is easy, since

Thus, (a) and (b) imply that x0 + kerA is the set of all solutions.
In theory, this theorem provides an excellent way of finding all solutions for linear equations, generalizing far beyond finite-dimensional vector spaces. (Note that the proof goes through verbatim for all vector spaces and linear transformations.) For instance, this exact result is used to describe all solutions of an inhomogeneous linear differential equation.
5.1.6 Inverting matrices
Section titled “5.1.6 Inverting matrices”So far, we have seen that the invertibility of a matrix A ∈ℝn×n is key to solving linear equations. However, we haven’t found a way to compute the inverse of a matrix yet.
Let’s recap what the inverse is in terms of linear transformations. If the columns of A are denoted by the vectors a1,…,an ∈ℝn, then A is the linear transformation that maps the standard basis vectors to these vectors:

If the direction of the arrows can be reversed, that is,

is a well-defined linear equation, then A−1 is called the inverse of A.
In light of all that we have seen in this chapter, the method for finding the inverse is simple: solve Ax = ei for each i where e1,…,en ∈ℝn is the standard basis.
Suppose that Axi = e i . Then, if b can be written as b = ∑ i=1nbie i, the vector x = ∑ i=1nbixi is the solution of Ax = b:

Thus, the inverse is the matrix whose i-th column is xi.
I know, this seems paradoxical: to find the solution of Ax = b, we need the inverse A−1. To find the inverse, we need to solve n equations. The answer is Gaussian elimination (Section 5.1.1), which gives us an exact computational method to obtain A−1. In the next section, we are going to put this into practice and write our matrix-inverting algorithm from scratch. Pretty awesome.
Bookmark
5.2 The LU decomposition
Section titled “5.2 The LU decomposition”In the previous chapter, I promised that you’d never have to solve a linear equation by hand. As it turns out, this task is perfectly suitable for computers. In this chapter, we will dive deep into the art of solving linear equations, developing the tools from scratch.
We start by describing the process of Gaussian elimination in terms of matrices. Why would we even do that? Because matrix multiplication can be performed extremely fast in modern computers. Expressing any algorithm in terms of matrices is a sure way to accelerate.
At the start, our linear equation Ax = b is given by the coefficient matrix

and at the end of the elimination process, A is transformed into the form

A(n−1) is upper diagonal; that is, all elements below its diagonal are 0.
Gaussian elimination performs this task one step at a time, focusing on consecutive columns. After the first elimination step, this is turned into the equation (5.1.1), described by the coefficient matrix

Can we obtain A(1) from A via multiplication with some matrix; that is, can we find G1 ∈ℝn×n such that A(1) = G1A holds?
Yes. By defining G1 as
.png)
(5.5)
we can see that A(1) = G1A is the same as performing the first step of Gaussian elimination. (Pick up a pen and paper and verify this by hand. It’s an excellent exercise.) G1 is lower diagonal; that is, all elements above its diagonal are 0. In fact, except for the first column, all elements below the diagonal are 0 as well. (Note that G1 depends on A.)
By analogously defining
.png)
(5.6)
we obtain A(2) = G2A(1) = G2G1A, a matrix that is upper diagonal in the first two columns. (That is, all elements are 0 below the diagonal, but only in the first two columns.)
We can continue this process until we obtain the upper triangular matrix
A(n−1) = Gn−1…G1A.
(5.7)
The algorithm is starting to shape up nicely. The Gi matrices are invertible, with inverses

and so on. Thus, by multiplying by their inverses one by one, we can express A as

Fortunately, we can calculate L := G1−1…Gn−1−1 by hand. After a quick computation, we obtain
.png)
(5.8)
which is lower diagonal. (Again, don’t be shy about verifying (5.8) by hand.) By defining the upper diagonal matrix U := A(n−1), we obtain the famous LU decomposition, factoring A into a lower and upper diagonal matrix:

Notice that with this algorithm, we perform two tasks for the price of one: factorizing A into the product of an upper diagonal and lower diagonal matrix, and performing Gaussian elimination.
From a computational standpoint, the LU decomposition is an extremely important tool. Since it is just a refashioned Gaussian elimination, its complexity is O(n3), just as we saw this earlier (Section 5.1.4).
Bad news: LU decomposition not always available. Since it is tied to Gaussian elimination, we can characterize its existence in similar terms. Recall that for the Gaussian elimination to successfully finish, the principal minors are required to be nonzero (Theorem 31). This is directly transferred to the LU decomposition.
Theorem 34. (Existence of the LU decomposition)
Let A ∈ℝn×n be an arbitrary square matrix, and let Mk be its k-th principal minor. If Mk≠0 for all k = 1,2,…,n − 1, then A can be written as

where L is a lower diagonal and U is an upper diagonal matrix. Moreover, the elements along the diagonal of L are equal to 1.
The gist is the same: everything is fine if we avoid division by 0 during the algorithm. Note that the LU algorithm doesn’t require a nonzero Mn = detA, that is, an invertible matrix!
After all this preparation, we are ready to put things into practice!
5.2.1 Implementing the LU decomposition
Section titled “5.2.1 Implementing the LU decomposition”To summarize the LU decomposition, it’s essentially the iteration of two steps:
- Calculate the elimination matrices of the input.
- Multiply the input by the elimination matrices, feeding the output back into the first step.
The plan is clear: first, we write a function that computes the elimination matrices and their inverses; then, we iteratively perform the elimination steps using matrix multiplication.
import numpy as np
def elimination_matrix( A: np.ndarray, step: int,): """ Computes the step-th elimination matrix and its inverse.
Args: A (np.ndarray): The matrix of shape (n, n) for which the LU decomposition is being computed. step (int): The current step of elimination, an integer between 1 and n-1
Returns: elim_mtx (np.ndarray): The step-th elimination matrix of shape (n, n) elim_mtx_inv (np.ndarray): The inverse of the elimination matrix of shape (n, n) """
n = A.shape[0] elim_mtx = np.eye(n) elim_mtx_inv = np.eye(n)
if 0 < step < n: a = A[:, step-1]/A[step-1, step-1] elim_mtx[step:, step-1] = -a[step:] elim_mtx_inv[step:, step-1] = a[step:]
return elim_mtx, elim_mtx_invNow, we are ready to perform the elimination steps.
def LU(A: np.ndarray): """ Computes the LU factorization of a square matrix A.
Args: A (np.ndarray): A square matrix of shape (n, n) to be factorized. It must be non-singular (invertible) for the decomposition to work.
Returns: L (np.ndarray): A lower triangular matrix of shape (n, n) with ones on the diagonal. U (np.ndarray): An upper triangular matrix of shape (n, n). """
n = A.shape[0] L = np.eye(n) U = np.copy(A)
for step in range(1, n): elim_mtx, elim_mtx_inv = elimination_matrix(U, step=step) U = np.matmul(elim_mtx, U) L = np.matmul(L, elim_mtx_inv)
return L, ULet’s test our function on a small matrix.
A = 10*np.random.rand(4, 4) - 5Aarray([[-4.61990165, -3.97616553, -1.34258661, 0.50835913], [-2.39491833, -2.3919011 , -1.3266581 , 2.8658852 ], [ 4.32658116, 0.43607725, 4.41630776, -4.46731714], [-0.68329877, 4.76659965, -1.13602896, -2.12305592]])L, U = LU(A)
print(f"Lower:\n{L}\n\nUpper:\n{U}"Lower:[[ 1. 0. 0. 0. ] [ 0.51839163 1. 0. 0. ] [ -0.93650936 9.94174964 1. 0. ] [ 0.14790331 -16.19246049 -1.18248523 1. ]]
Upper:[[-4.61990165e+00 -3.97616553e+00 -1.34258661e+00 5.08359130e-01] [ 0.00000000e+00 -3.30690182e-01 -6.30672445e-01 2.60235608e+00] [ 0.00000000e+00 0.00000000e+00 9.42895038e+00 -2.98632067e+01] [ 1.11022302e-16 -8.88178420e-16 1.77635684e-15 4.62750317e+00]]Is the result correct? Let’s test it by multiplying L and U together to see if it gives A back.
np.allclose(np.matmul(L, U), A)TrueOverall, the LU decomposition is a highly versatile tool, used as a stepping stone in the implementation of essential algorithms. One of them is computing the inverse matrix, as we shall see next.
5.2.2 Inverting a matrix, for real
Section titled “5.2.2 Inverting a matrix, for real”So far, we have talked a lot about the inverse matrix. We explored the question of invertibility from several angles, in terms of the kernel and the image, the determinant, and the solvability of linear equations.
However, we haven’t yet talked about actually computing the inverse. With the LU decomposition, we obtain a tool that can be used for this purpose. How? By plugging in a lower triangular matrix into the Gaussian elimination process, we get its inverse as a side effect. So, we
- calculate the LU decomposition A = LU,
- invert the lower triangular matrices L and UT ,
- use the identity (U−1)T = (UT )−1 to get U−1,
- multiply L−1 and U−1 to finally obtain A−1 = U−1L−1.
That’s a plan! Let’s start with inverting lower triangular matrices.
Let L ∈ℝn×n be an arbitrary lower triangular matrix. Following the same process that led to (5.7), we obtain

where D, the final result of Gaussian elimination, is a diagonal matrix

and the Gi-s are the elimination matrices defined by (5.5), (5.6), and so on.
Since the inverse of
is simply
, we can express
as

We can implement this very similarly to the LU decomposition; we can even reuse our elimination_matrix function.
def invert_lower_triangular_matrix(L: np.ndarray): """ Computes the inverse of a lower triangular matrix.
Args: L (np.ndarray): A square lower triangular matrix of shape (n, n). It must have non-zero diagonal elements for the inversion to succeed.
Returns: np.ndarray: The inverse of the lower triangular matrix L, with shape (n, n). """ n = L.shape[0] G = np.eye(n) D = np.copy(L)
for step in range(1, n): elim_mtx, _ = elimination_matrix(D, step=step) G = np.matmul(elim_mtx, G) D = np.matmul(elim_mtx, D)
D_inv = np.eye(n)/np.diagonal(D) # NumPy performs this operation elementwise
return np.matmul(D_inv, G)With this done, we are ready to invert any matrix (that is actually invertible).
We are almost at the finish line. Every component is ready; the only thing left to do is to put them together. We can do this with a few lines of code.
def invert(A: np.ndarray): """ Computes the inverse of a square matrix using its LU decomposition.
Args: A (np.ndarray): A square matrix of shape (n, n). The matrix must be non-singular (invertible) for the inversion to succeed.
Returns: np.ndarray: The inverse of the input matrix A, with shape (n, n). """ L, U = LU(A) L_inv = invert_lower_triangular_matrix(L) U_inv = invert_lower_triangular_matrix(U.T).T return np.matmul(U_inv, L_inv)Voilà! Witness the result with your own eyes.
A = np.random.rand(3, 3)A_inv = invert(A)
print(f"A:\n{A}\n\nA^{-1}:\n{A_inv}\n\nAA^{-1}:\n{np.matmul(A, A_inv)}"A:[[0.17180745 0.79269571 0.36879642] [0.37772174 0.94712553 0.55310582] [0.93418085 0.38813821 0.51581695]]
A^{-1}:[[ 9.14230036 -8.87123133 2.97602074] [ 10.74480189 -8.5427258 1.47801811] [-24.64252111 22.49459369 -4.56327945]]
AA^{-1}:[[ 1.00000000e+00 -1.37050081e-15 1.56962305e-17] [-4.06841165e-16 1.00000000e+00 -4.50714074e-16] [ 1.26848123e-14 -1.04564970e-14 1.00000000e+00]]To test the correctness of our invert function, we quickly check the results on a few randomly generated matrices.
for _ in range(1000): n = np.random.randint(1, 10) A = np.random.rand(n, n) A_inv = invert(A) if not np.allclose(np.matmul(A, A_inv), np.eye(n), atol=1e-5): print("Test failed."Since there is no error message above, the function is (probably) correct.
What seemed complex and abstract a few chapters ago is now in our hands. We can invert any matrix, not with built-in functions, but with one that we wrote from scratch. I love these moments when the pieces are finally put together, and everything clicks. Sit back, relax, and appreciate the journey that got us here!
5.2.3 How to actually invert matrices
Section titled “5.2.3 How to actually invert matrices”Of course, our LU decomposition!matrices, invertingimplementation is far from optimal. When working with NumPy arrays, we can turn to the built-in functions. In NumPy, this is np.linalg.inv.
A = np.random.rand(3, 3)A_inv = np.linalg.inv(A)
print(f"A:\n{A}\n\nNumPy’s A^{-1}:\n{A_inv}\n\nAA^{-1}:\n{np.matmul(A, A_inv)}"A:[[0.08503998 0.31186637 0.71032538] [0.48973954 0.77358354 0.96303592] [0.31250848 0.14359491 0.05593863]]
NumPy’s A^{-1}:[[ 2.13348825 -1.89861153 5.59470678] [-6.14268693 4.87769374 -5.97239945] [ 3.84931433 -1.91423645 1.95236829]]
AA^{-1}:[[ 1.00000000e+00 -1.86546922e-16 2.74435800e-16] [-1.62367293e-16 1.00000000e+00 9.21871975e-17] [-1.41854334e-18 3.64838601e-17 1.00000000e+00]]Let’s compare the runtime of our implementation and NumPy’s.
from timeit import timeit
n_runs = 100size = 100A = np.random.rand(size, size)
t_inv = timeit(lambda: invert(A), number=n_runs)t_np_inv = timeit(lambda: np.linalg.inv(A), number=n_runs)
print(f"Our invert: \t{t_inv} s")print(f"NumPy's invert: \t{t_np_inv} s")print(f"Performance improvement: \t{t_inv/t_np_inv} times faster")Our invert: 14.586225221995846 sNumPy’s invert: 0.46499890399718424 sPerformance improvement: 31.368300218798304 times fasterA massive improvement. Nice! (Don’t forget that the execution time isLU decomposition!matrices, inverting hardware-dependent.) Why is NumPy that much faster? There are two main reasons. First, it directly calls the SGETRI function from LAPACK, which is extremely fast. Second, according to its documentation ( https://www.netlib.org/lapack/explore-html/da/d28/group__getri_gaa3bf1bb1432917f0e5fdf4c48bd6998c.html), SGETRI uses a faster algorithm:
"""SGETRI computes the inverse of a matrix using the LU factorizationcomputed by SGETRF.
This method inverts U and then computes inv(A) by solving the systeminv(A)*L = inv(U) for inv(A). """So, NumPy calls the LAPACK function, which uses LU factorization in turn. (I am not particularly adept at digging through Fortran code that is older than I am, so let me know if I am wrong here. Nevertheless, the fact that state-of-the-art frameworks still make calls to this ancient library is a testament to its power. Never underestimate old technologies like LAPACK and Fortran.)
Are there any other applications of the powerful LU decomposition that we’ve just learned? Glad you asked! Of course there is; that’s the beauty of math. There’s always a new and unexpected application even for the oldest of tools. This time, we’ll finally see how to compute determinants fast! (And also slow.)
Bookmark
5.3 Determinants in practice
Section titled “5.3 Determinants in practice”In the theory and practice of mathematics, the development of concepts usually has a simple flow. Definitions first arise from vague geometric or algebraic intuitions, eventually crystallizing in mathematical formalism.
However, mathematical definitions often disregard practicalities. For a very good reason, mind you! Keeping practical considerations out of sight gives us the power to reason about structure effectively. This is the strength of abstraction. Eventually, if meaningful applications are found, the development flows toward computational questions, putting speed and efficiency onto the horizon.
The epitome of this is neural networks themselves. From theoretical constructs to state-of-the-art algorithms that run on your smartphone, machine learning research followed this same arc.
This is also what we experience in this book on a microscopic level. Among many other examples, think about determinants. We introduced the determinant as the orientation of column vectors and the parallele-piped volume defined by them. Still, we haven’t really worked on computing them in practice. Sure, we gave a formula or two, but it is hard to decide which one is the most convoluted. All of them are.
On the other hand, the mathematical study of determinants yielded a ton of useful results: invertibility of linear transformations, characterization of Gaussian elimination, and many more (and even more to come.).
In this section, we are ready to pay off our debts and develop tools to actually compute determinants. As before, we will take a straightforward approach and use one of the previously derived determinant formulas. Spoiler alert: This is far from optimal, so we’ll find a way to compute the determinant with high speed.
5.3.1 The lesser of two evils
Section titled “5.3.1 The lesser of two evils”Let’s recall what we know about determinants (Definition 20) so far. Given a matrix A ∈ℝn×n, its determinant detA quantifies the volume distortion of the linear transformation x →Ax. That is, if e1,…,en is the standard orthonormal basis, then informally speaking,

We have derived two formulas to compute this quantity. Initially, we described the determinant in terms of summing over all permutations:

This is difficult to understand, let alone to programmatically compute. So, a recursive formula is derived, which we can also use. It states that

where Ai,j is the matrix obtained by deleting the i-th row and j-th column of A. Which one would you rather use? Take a few minutes to figure out your reasoning.
Unfortunately, there are no right choices here. With the permutation formula, one has to find a way to generate all permutations first, then calculate their signs. Moreover, there are n! unique permutations in Sn, so this sum has a lot of terms. Using this formula seems extremely difficult, so we will go with the recursive version. Recursion has its issues (as we are about to see very soon), but it is easy to handle from a coding standpoint. Let’s get to work!
5.3.2 The recursive way
Section titled “5.3.2 The recursive way”Let’s put the formula

under our magnifying glass. If A is an n×n matrix, then A1,j (obtained from A by deleting its first row and j-th column) is of size (n− 1) × (n− 1). This is a recursive step. For each n×n determinant, we have to calculate n pieces of (n− 1) × (n− 1) determinants, and so on.
By the end, we have a lots of 1 × 1 determinants, which are trivial to calculate. So, we have a boundary condition, and with that, we are ready to put these together.
def det(A: np.ndarray): """ Recursively computes the determinant of a square matrix A.
Args: A (np.ndarray): A square matrix of shape (n, n) for which the determinant is to be calculated.
Returns: float: The determinant of matrix A.
Raises: ValueError: If A is not a square matrix. """
n, m = A.shape
# making sure that A is a square matrix if n != m: raise ValueError("A must be a square matrix."
if n == 1: return A[0, 0]
else: return sum([(-1)**j*A[0, j]*det(np.delete(A[1:], j, axis=1)) for j in range(n)])Let’s test the det function out on a small example. For 2 × 2 matrices, we can easily calculate the determinants using the rule

A = np.array([[1, 2], [3, 4]])det(A) # should be -2np.int64(-2)It seems to work. So far, so good. What is the issue? Recursion. Let’s calculate the determinant of a small 10 × 10 matrix, measuring the time it takes.
from timeit import timeit
A = np.random.rand(10, 10)t_det = timeit(lambda: det(A), number=1)
print(f"The time it takes to compute the determinant of a 10 x 10 matrix: {t_det} secondsThe time it takes to compute the determinant of a 10 x 10 matrix:63.98369195000123 secondsThat was long and unbearable. For such a simple task, this feels like an eternity.
For n×n inputs, we call the det function recursively n times, on (n− 1) × (n− 1) inputs. That is, if an denotes the time complexity of our algorithm for an n ×n matrix, then, due to the recursive step, we have

which explodes really fast. In fact, an = O(n!), which is the dreaded factorial complexity. Unlike some other recursive algorithms, caching doesn’t help either. There are two reasons for this: sub-matrices rarely match, and numpy.ndarray objects are mutable, thus not hashable.
In practice, n can be in the millions, so this formula is utterly useless. What can we do? Simple: LU decomposition.
5.3.3 How to actually compute determinants
Section titled “5.3.3 How to actually compute determinants”Besides the two formulas, we have seen lots of useful properties of matrices and determinants. Can we apply what we have learned so far to simplify the problem?
Let’s consider the LU decomposition. According to this, if detA≠0, then A = LU, where L is lower triangular and U is upper triangular. Since the determinant behaves nicely with respect to matrix multiplication (see equation (4.11)), we have

Seemingly, we made our situation worse: instead of one determinant, we have to deal with two. However, L and U are rather special, as they are triangular. It turns out that computing a triangular matrix’s determinant is extremely easy. We just have to multiply the elements on the diagonal together!
Theorem 35. (Determinant of a triangular matrix)
Let A ∈ℝn×n be a triangular matrix. (That is, it is either lower or upper triangular.) Then,

Proof.Suppose that A is lower triangular. (That is, all elements above its diagonal are 0.) According to the recursive formula for detA, we have

Because A is lower triangular, a1,j = 0 if j >1. Thus,

A1,1 = (aij)i,j=2n is also lower triangular. By iterating the previous step, we obtain

which is what we had to show.
If A is upper triangular, its transpose AT is lower triangular. Thus, we can apply the previous result, so

holds as well.
Back to our original problem. Since the diagonal L is constant 1 (see (5.8)), as guaranteed by the LU decomposition, we have

So, the algorithm to compute the determinant is quite simple: get the LU decomposition, then calculate the product of U’s diagonal. Let’s put this into practice!
def fast_det(A: np.ndarray): """ Computes the determinant of a square matrix using LU decomposition.
Args: A (np.ndarray): A square matrix of shape (n, n) for which the determinant needs to be computed. The matrix must be non-singular (invertible).
Returns: float: The determinant of the matrix A. """ L, U = LU(A) return np.prod(np.diag(U))Yes, that simple. Let’s see how it performs!
A = np.random.rand(10, 10)
t_fast_det = timeit(lambda : fast_det(A), number=1)print(f"The time it takes to compute the determinant of a 10 x 10 matrix: {t_fast_det} secondsThe time it takes to compute the determinant of a 10 x 10 matrix:0.0008458310039713979 secondsIt’s faster by a huge margin. How much faster?
print(f"Recursive determinant: \t{t_det} sprint(f"LU determinant: \t{t_fast_det} sprint(f"Performance improvement: \t{t_det/t_fast_det} times fasterRecursive determinant: 63.98369195000123 sLU determinant: 0.0008458310039713979 sPerformance improvement: 75645.95250065446 times fasterThat’s quite an insane improvement! This can be even faster if we use a better implementation of the LU decomposition algorithm (for instance, scipy.linalg.lu, which relies on our old friend LAPACK).
I get emotional just by looking at this result. See how far we can go with a bit of linear algebra? This is why understanding the fundamentals such as Gaussian elimination is essential. Machine learning and deep learning are still very new fields, and even though an insane amount of research power is being put into it, moments like these happen all the time. Simple ideas often give birth to new paradigms.
Bookmark
5.4 Summary
Section titled “5.4 Summary”In this chapter, we have looked at matrices from the perspective of linear equation systems, i.e., equations of the form

Not surprisingly, these are described by matrices, and the above is equivalent to the expression Ax = b. Solving linear equations is an ancient art, so why are we talking about it in the age of AI?
Remember: It’s only AI if you are talking to investors. Deep down, it’s linear algebra, calculus, and probability theory.
We wanted to solve linear equations, which led us to Gaussian elimination (well, led Gauss to Gaussian elimination). Which led us to the LU decomposition. Which led us to fast matrix inversion, and a bunch of other innovations on which our current technology is built on. Let me tell you, fast matrix multiplication and inversion are the bread and butter of computational linear algebra, and they all stem from that aforementioned ancient art of solving linear equations.
Let’s recap the feats that we’ve achieved in this chapter one by one:
- solving linear equations by Gaussian elimination,
- characterizing the invertibility of matrices in terms of linear equations,
- discovering a matrix factorization technique called LU decomposition,
- building a crazy-fast matrix-inverting algorithm using the LU decomposition,
- and building a crazy-fast determinant-computing algorithm using – drumroll! – the LU decomposition.
However, we are not done with matrices. Recall the relationship we established between them and linear transformations, viewing matrices as data transforms that distort the underlying feature space. As it turns out, if we are looking from the right perspective, this distortion is always a stretching. Well, almost always. Well, almost a stretching.
Well, that was too many wells, so let’s clear all of it up in the next chapter, diving into eigenvalues and eigenvectors. Let’s go!
Bookmark
5.5 Problems
Section titled “5.5 Problems”Problem 1. Show that the product of upper triangular matrices is upper triangular. Similarly, show that the product of lower triangular matrices is lower triangular. (We have used these facts extensively in this section but didn’t give a proof. So, this is an excellent time to convince yourself about this if you haven’t already.)
Problem 2. Write a function that, given an invertible square matrix A ∈ℝn×n and a vector b ∈ℝn, finds the solution of the linear equation Ax = b. (This can be done with a one-liner if you use one of the tools we have built here.)
Problem 3. Before we wrap this chapter up, let’s go back to the definition of determinants. Even though there are lots of reasons against using the determinant formula, we have one for it: it is a good exercise, and implementing it will deepen your understanding. So, in this problem, you are going to build

one step at a time.
(i) Implement a function that, given an integer n, returns all permutations of the set {0,1,…,n − 1}. Represent each permutation σ as a list. For example,
[2, 0, 1]would represent the permutation σ, where σ(0) = 2,σ(1) = 0, and σ(2) = 1.
(ii) Let σ ∈Sn be a permutation of the set {0,1,…,n − 1}. Its inversion number is defined by

where j ⋅j denotes the number of elements in the set. Essentially, inversion describes the number of times a permutation reverses the order of a pair of numbers.
Turns out, the sign of σ can be written as

Implement a function that first calculates the inversion number, then the sign of an arbitrary permutation. (Permutations are represented like in the previous problem.)
(iii) Put the solutions for Problem 1. and Problem 2. together and calculate the determinant of a matrix using the permutation formula. What do you think the time complexity of this algorithm is?