Invert a square matrix by Gauss-Jordan elimination, without np.linalg.inv.
Glue an identity matrix onto the right of A to get an (n, 2n) block, then
row reduce the left half all the way to the identity. Whatever the right half
becomes is A^-1, because every row operation is a left multiplication and
together they spell out A^-1 A | A^-1 I.
Use partial pivoting: at each column, swap in the row whose entry has the
largest absolute value. If the best pivot is smaller than 1e-12 the matrix is
singular, so return None.
Unlike row echelon form you have to eliminate above each pivot as well, so the left block ends up as the identity and not just triangular.
def matrix_inverse(A):
Input
matrix_inverse(np.array([[4.0, 7.0], [2.0, 6.0]]))
Output
array([[ 0.6, -0.7],
[-0.2, 0.4]])
Reasoning
The determinant is 4 * 6 - 7 * 2 = 10. The inverse is [[6, -7], [-2, 4]] / 10, and Gauss-Jordan elimination gives the same result.
1e-12, return None.np.linalg.inv.Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell