Matrices: Matrices in Python
Row reduction and determinant
Python provides row and column operations to compute reduction processes in matrices numerically, but calculate the reduced row echelon form of a matrix with the command rref. This allows you to perform the method of row reduction for calculating an inverse matrix.
The inverse of a matrix computing
>>> import numpy as np
>>> import numpy.linalg as la
>>> import sympy as sy
>>> # invertible matrix:
>>> A = sy.Matrix([[3, 1, -4], [-1, 0, 2], [1, 1, -1]]); A
Matrix([
[ 3, 1, -4],
[-1, 0, 2],
[ 1, 1, -1]])
>>> I = sy.eye(3); I
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> AI = A.row_join(I); AI # augmented matrix
Matrix([
[ 3, 1, -4, 1, 0, 0],
[-1, 0, 2, 0, 1, 0],
[ 1, 1, -1, 0, 0, 1]])
>> GAI = AI.rref(); GAI[0] # reduced row echelon form
Matrix([
[1, 0, 0, 2, 3, -2],
[0, 1, 0, -1, -1, 2],
[0, 0, 1, 1, 2, -1]])
>>> GAI[0][:, 3:] # submatrix equal to inverse of A
Matrix([
[ 2, 3, -2],
[-1, -1, 2],
[ 1, 2, -1]])
>>> la.inv(np.array(A.tolist(), float)) # inverse via numpy.linalg.inv
array([[ 2., 3., -2.],
[-1., -1., 2.],
[ 1., 2., -1.]])
The determinant of the matrix \(A\) in the above example can be calculated with the command det, and the result shows that the matrix is invertible. We give below also an example of a non-invertible matrix because the determinant is equal to 0 and the reduced echelon form is not equal to an identity matrix. If you're still trying to calculate the inverse, you actually get a result with a matching warning. In addition, be always on guard for numerical rounding errors in calculations.
Determinant van een matrix
>>> A # invertible matrix A
Matrix([
[ 3, 1, -4],
[-1, 0, 2],
>>> sy.det(A) # determinant ofn A
-1
>>> # non-invertible matrix B:
>>> B = sy.Matrix([[1, -2, -2], [1, 14, 14], [-4, -24, -24]]); B
Matrix([
[ 1, -2, -2],
[ 1, 14, 14],
[-4, -24, -24]])
>>> sy.det(B) # determinant of B
0
>>> np.rank(B) # rank of B
2
>>> B.rref()[0] # reduced row echelon form of B
Matrix([
[1, 0, 0],
[0, 1, 1],
[0, 0, 0]])
>>> la.inv(np.array(B.tolist(), float)) # attempt to compute inverse of B
Traceback (most recent call last):
...
numpy.linalg.linalg.LinAlgError: Singular matrix