Why is linear algebra useful? It turns out that most things in the world are pretty linear, or can be modeled as linear systems through [clever techniques](https://chillphysicsenjoyer.substack.com/p/using-linear-algebra-to-predict-a). On top of that, computers are very good at working with data stored in matrices, the core of linear algebra. So linear algebra is a super powerful tool for understanding the world. ### Vectors A vector is a series of numbers stacked vertically, i.e. $x = \begin{bmatrix}1 \\ 2 \\ 3\end{bmatrix}$ Taking the transpose of a vector makes it horizontal: $x^{\mathrm{T}} = \begin{bmatrix}1 & 2 & 3\end{bmatrix}$ We can multiply vectors in a few ways, including the outer product and cross product, but the most relevant is the dot product, also known as the inner product. #### Dot product $a\cdot b = a^{\mathrm{T}}b = \begin{bmatrix}1 & 2 & 3\end{bmatrix} \begin{bmatrix}4 \\ 5 \\ 6\end{bmatrix} = 1\cdot 4 + 2 \cdot 5 + 3 \cdot 6$ The **length** of a vector $x$ is the square root of its dot product with itself: $\lvert \lvert x \rvert \rvert = \sqrt{ x_{1}^{2}+x_{2}^{2} + \dots + x_{n}^{2} } = \sqrt{ x\cdot x }$ Additionally, if $a\cdot b=0$, then we can say the vectors are **orthogonal**, or perpendicular in each of their dimensions. We can show this works in 2D with the Pythagorean theorem: if $a$ and $b$ are perpendicular vectors the hypotenuse is $c=b-a$, then $\lvert \lvert a \rvert \rvert^{2} + \lvert \lvert b \rvert \rvert^{2} = \lvert \lvert c \rvert \rvert^{2}$. Rewriting this as $a\cdot a + b\cdot b = (b-a)\cdot(b-a) = b\cdot b -2a\cdot b + a\cdot a$, we see that the Pythagorean theorem holds only when $a\cdot b=0$. #### Outer product: Not even useful enough to get its own symbol but worth mentioning to illustrate vector multiplication: $ab^{\mathrm{T}} = \begin{bmatrix}1 \\ 2 \\ 3\end{bmatrix} \begin{bmatrix}4 & 5 & 6\end{bmatrix} = \begin{bmatrix}1\cdot 4 & 1\cdot 5 & 1 \cdot 6 \\ 2\cdot 4 & 2\cdot5 & 2\cdot 6 \\ 3 \cdot 4 & 3 \cdot 5 & 3 \cdot 6 \end{bmatrix}$ #### Linear Independence Vectors are linearly dependent (think redundant) if at least one of them is a linear combination of the others. In other words, the vectors $v_{1}, v_{2}, \dots v_{k}$ are linearly independent when $a_{1}v_{1}+a_{2}v_{2}+\dots+a_{k}v_{k}=0$ only holds if $a_{1}= a_{2} =\dots= a_{k}=0$ . A set of vectors which are ### Matrices A matrix is a vector with multiple columns. The **column space** of a matrix $A$, denoted $C(A)$, is the set of all vectors which are linear combinations of the column vectors of $A$. Multiplying vector $b$ by matrix $A$ transforms it into a vector in the column space of $A$; you scale the column vectors of $A$ by the corresponding values of $b$: $ Ab = \begin{bmatrix} | & | & | \\ a_{1} & a_{2} & a_{3} \\ | & | & | \end{bmatrix} \begin{bmatrix} 1 \\ 2 \\ 3 \end{bmatrix} = a_{1} \cdot 1 + a_{2} \cdot 2 + a_{3} \cdot 3 $ The **null space** of $A$, denoted $N(A)$, is the set of all vectors such that $Ab =0$. When you multiply matrix $B$ with matrix $A$, you transform each of $B s column vectors: $AB = A\left[{\begin{array}{c c c c c}{{\mid}}&{{\mid}}&{{}}&{{\mid}}\\ {{b_{1}}}&{{b_{2}}}&{{\ldots}}&{{b_{p}}}\\ {{\mid}}&{{\mid}}&{{}}&{{\mid}}\end{array}}\right]=\left[{\begin{array}{c c c c}{{\mid}}&{{\mid}}&{{}}&{{\mid}}\\ {{A b_{1}}}&{{A b_{2}}}&{{\ldots}}&{{A b_{p}}}\\ {{\mid}}&{{\mid}}&{{}}&{{\mid}}\end{array}}\right]$ ### Solving Linear Systems Let's start with three equations and three unknowns: $ \begin{align} 15x -3y -z = 3800 \\ -3x + 18y -6z = 1200\\ -4x -y + 12z = 2350 \end{align} $ We can rewrite this using matrices. We put ${} x$, ${} y$, and ${} z$ into a vector $\vec{x}$ and $ \underbrace{ \begin{bmatrix} 15 & -3 & -1 \\ -3 & 18 & -6 \\ -4 & -1 & 12 \end{bmatrix} }_{ A } \underbrace{ \begin{bmatrix} x \\ y \\ z \end{bmatrix} }_{ \vec{x} } = \underbrace{ \begin{bmatrix} 3800 \\ 1200 \\ 2350 \end{bmatrix} }_{ \vec{b} } $ It turns out that most problems can be turned into the form $Ax = b$ where $A$ is a coefficient matrix, $x$ is a vector of unknowns, and $b$ is a vector representing the right hand side. We can make a computer solve this for us easily: ```python import numpy as np A = np.array([[15, -3, -1],               [-3, 18, -6],               [-4, -1, 12]]) b = np.array([3800, 1200, 2350]) x = np.linalg.solve(A, b) print(x) ``` How does this work? ### Gaussian Elimination Consider if instead the coefficient matrix was in "Row Echelon form," shown here: $ \begin{bmatrix} P_{1} & ? & ? \\ 0 & P_{2} & ? \\ 0 & 0 & P_{3} \end{bmatrix} \begin{bmatrix} x \\ y \\ z \end{bmatrix} = \begin{bmatrix} ? \\ ? \\ ? \end{bmatrix} $ The first nonzero value in each row is called a pivot, labelled $P_{1}, P_{2},$ and $P_{3}$. Sidenote: If there are rows which are all zero (fewer pivots than rows), there is either no solution (if the right side is nonzero) or infinitely many solutions (if the right hand side is zero). No solutions means the equations contradict each other and infinitely many means the equations are redundant. See if you can figure out why. We can easily solve for $z = \frac{?}{P_{3}}$, then plug that in to solve for y, and plug that in to solve for x. This systematic approach is called back-substitution. We can manipulate our original coefficient matrix into Row Echelon form using Gaussian Elimination. We use the matrix version of multiplying both sides of an equation and subtracting it from another to make all the coefficients below our pivot columns zero. The 'equation' of the pivot row and the corresponding right hand side are multiplied by the coefficient ratio which would cancel out each of the coefficients below the pivot, then subtracted from both sides for each row that needs a zero. ### LU Decomposition To make this more computationally efficient for different right values of the right hand side, we can store the steps in matrices using an algorithm called LU Decomposition. The trick is decomposing $A$ into an upper triangular matrix $U$ (through gaussian elimination) and a lower triangular matrix $L$ (from the values we multiplied the rows by in the elimination steps) such that $A = LU$. Then we can backsubstitute from the outside in, first using forward substitution (back substitution for lower triangular matrices) on $L$ to solve for $Ux=d$, then doing back-substitution on $U$ to solve for $x$. $ \begin{align} Ax &= LUx \text{ ← LU Decomposition}\\ L\underbrace{ (Ux) }_{ d } &= b \\ Ld &= b \text{ ← forward substitution} \\ Ux &= d\text{ ← back substitution} \end{align} $ Additional algorithmic improvement include: - swapping rows to reduce rounding errors and storing the swaps in a vector $p$ - replacing the zeros in the L matrix with the values in the U matrix to save storage - monitoring near-zero terms for singular matrices which have no solutions #### LU Python Implementation An example implementation of this algorithm in code is given below: ```python def lu_decompose(A): """Returns L, U such that A = L @ U.""" n = A.shape[0] L = np.eye(n) U = A.copy().astype(float) for k in range(n - 1): for i in range(k + 1, n): f = U[i, k] / U[k, k] L[i, k] = f U[i, k:] -= f * U[k, k:] return L, U def forward_sub(L, b): """Solves L @ d = b (forward substitution).""" n = len(b) d = np.zeros(n) d[0] = b[0] for i in range(1, n): d[i] = b[i] - L[i, :i] @ d[:i] return d def back_sub(U, d): """Solves U @ x = d (back substitution).""" n = len(d) x = np.zeros(n) x[-1] = d[-1] / U[-1, -1] for i in range(n - 2, -1, -1): x[i] = (d[i] - U[i, i+1:] @ x[i+1:]) / U[i, i] return x def inverse(A): """Returns the inverse of A using LU decomposition.""" n = A.shape[0] L, U = lu_decompose(A) A_inv = np.zeros_like(A) for i in range(n): e = np.zeros(n) e[i] = 1 d = forward_sub(L, e) A_inv[:, i] = back_sub(U, d) return A_inv ``` In practice numpy will do this for you in the background, and even check if your matrix can be solved with faster algorithms such as Thomas (for diagonal and banded matrices) or Cholesky (for symmetric matrices). ### Iterative Methods ## What about when the # of equations $\neq$ # of unknowns? ### SVD ## Solving Differential Equations