Notebook for 2023-02-08
In this lecture, we discussed forward and backward substitution for triangular matrices, and the basic Gaussian elimination algorithm without pivoting. We copy in the algorithms here and illustrate them, as well as illustrating what we would really want to do in Julia using the LinearAlgebra
package rather than rolling our own.
Triangular solves
LU factorization gives us a unit lower triangular matrix and an upper triangular matrix as factors, so let's start by figuring out how to solve systems with them.
forward_subst_unit (generic function with 1 method)
test_forward_subst (generic function with 1 method)
1.0
-1.0
2.0
1.0
-1.0
2.0
backward_subst (generic function with 1 method)
test_backward_subst (generic function with 1 method)
5.33333
-6.33333
3.0
5.33333
-6.33333
3.0
Gaussian elimination
Let's write a version of the LU factorization routine that overwrites $A$ with the factors.
my_lu! (generic function with 1 method)
It's convenient to also have a version that does not overwrite the underlying matrix.
my_lu (generic function with 1 method)
test_my_lu (generic function with 1 method)
0.0
If we want to solve linear systems, we can do forward and backward substitution, either using the triangular views or directly on the packed form of the factorization.
test_lu_solve1 (generic function with 1 method)
1.2947551941976476e-15
test_lu_solve2 (generic function with 1 method)
2.858578470698463e-15
Finally, let's look at how to do the whole thing end-to-end with the built-in LU routines in Julia. The factorization we compute in this case includes pivoting for stability, which is why the $L$ and $U$ factors are different from those before.
LU{Float64, Matrix{Float64}, Vector{Int64}}
L factor:
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.333333 1.0 0.0
0.666667 0.5 1.0
U factor:
3×3 Matrix{Float64}:
3.0 6.0 10.0
0.0 2.0 3.66667
0.0 0.0 -0.5
The result with pivoting should look like $PA = LU$; note that Julia stores the permutation as a reordered index vector rather than as a matrix.
3×3 Matrix{Float64}:
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
We can solve the linear system either by using the factorization object or by using the pieces of the factorization (as we did before). The former approach is usually simpler.
1.44329e-15
-4.21885e-15
2.22045e-15
1.44329e-15
-4.21885e-15
2.22045e-15