invert a 3x3 matrix in python

To invert a 3x3 matrix in Python, we can use the numpy library which provides a convenient function called inv(). Here's the code:

main.py
import numpy as np

# define your 3x3 matrix as a numpy array
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# invert the matrix using the inv() function
inverse_matrix = np.linalg.inv(matrix)

# print the result
print(inverse_matrix)
280 chars
13 lines

Output:

main.py
[[-0.94444444 -0.11111111  0.72222222]
 [ 0.44444444  0.22222222 -0.11111111]
 [-0.05555556  0.11111111  0.27777778]]
118 chars
4 lines

Note that if your matrix is singular (i.e., has no inverse), the inv() function will raise a LinAlgError exception.

related categories

gistlibby LogSnag