w3resource

NumPy: Compute the inverse of a given matrix


Write a NumPy program to compute the inverse of a given matrix.

Sample Solution :

Python Code :

# Import the NumPy library and alias it as 'np'
import numpy as np

# Create a 2x2 NumPy array 'm' containing specific values
m = np.array([[1,2],[3,4]])

# Display the original matrix 'm'
print("Original matrix:")
print(m)

# Calculate the inverse of the matrix 'm' using np.linalg.inv() function
result =  np.linalg.inv(m)

# Display the inverse of the matrix 'm'
print("Inverse of the said matrix:")
print(result) 

Sample Output:

Original matrix:
[[1 2]
 [3 4]]
Inverse of the said matrix:
[[-2.   1. ]
 [ 1.5 -0.5]]

Explanation:

m = np.array([[1,2],[3,4]]): This statement creates a 2x2 NumPy array m with the specified elements.

result = np.linalg.inv(m): This line computes the inverse of the matrix m. The inverse of a square matrix A (if it exists) is another matrix, denoted as A^(-1), such that their product results in the identity matrix (A * A^(-1) = I). In this case, the inverse of the 2x2 matrix m is calculated as follows:

1/(ad-bc) * [[d, -b], [-c, a]]

where a, b, c, and d are the elements of the matrix, and ad-bc is the determinant.

For the given matrix m, the inverse is calculated as:

1/((1*4)-(2*3)) * [[4, -2], [-3, 1]]

1/(-2) * [[4, -2], [-3, 1]]

-0.5 * [[4, -2], [-3, 1]]

resulting in the inverse matrix [[-2., 1.], [1.5, -0.5]].

Python-Numpy Code Editor: