w3resource

NumPy: Compute the inverse of a given matrix

NumPy: Linear Algebra Exercise-12 with Solution

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:

Previous: Write a NumPy program to compute the determinant of an array.
Next: Write a NumPy program to calculate the QR decomposition of a given matrix.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/linear-algebra/numpy-linear-algebra-exercise-12.php