The function that is useful in factorizing a matrix into a lower and upper triangular matrix is available in scipy.linalg as the lu function.
In order to understand how LU factorization works, let us go through the following code snippets:
- Define a matrix:
A = np.array([[2., 1., 1.], [1., 3., 2.], [1., 0., 0.]])
- Import relevant classes and packages:
import scipy.linalg as linalg
- Calculate the LU matrices using the lu function in scipy.linalg:
P, L, U = scipy.linalg.lu(A)
- Check the output of L:
print(L)
[[ 1. 0. 0. ] [ 0.5 1. 0. ] [ 0.5 -0.2 1. ]]
- Check the output of Uprint(U):
[[ 2. 1. 1. ] [ 0. 2.5 1.5] [ 0. 0. -0.2]]
Note that, in the preceding outputs, L is a lower triangular matrix (all the elements in the upper half of the matrix are 0) and U is an upper triangular matrix.
Once we obtain the L and U matrices, let us cross-check if the matrix multiplication of the two results in the input matrix A.
The matrix multiplication of L, U is as follows:
np.dot(L,U)
[[ 2.00000000e+00 1.00000000e+00 1.00000000e+00]
[ 1.00000000e+00 3.00000000e+00 2.00000000e+00]
[ 1.00000000e+00 -2.77555756e-17 0.00000000e+00]]
In the preceding output, we notice that it is the same as the input matrix A, which we created earlier.