w3resource

Solve Linear algebra problems with NumPy and SciPy

NumPy: Integration with SciPy Exercise-3 with Solution

Write a NumPy program that creates a NumPy array and uses SciPy to solve a linear algebra problem. For example, finding the determinant, inverse, and eigenvalues of a matrix.

Sample Solution:

Python Code:

# Import necessary libraries
import numpy as np
from scipy import linalg

# Create a NumPy array (matrix)
matrix = np.array([[4, 2], [3, 1]])

# Find the determinant of the matrix using SciPy
determinant = linalg.det(matrix)

# Find the inverse of the matrix using SciPy
inverse = linalg.inv(matrix)

# Find the eigenvalues of the matrix using SciPy
eigenvalues, eigenvectors = linalg.eig(matrix)

# Print the matrix
print("Matrix:")
print(matrix)

# Print the determinant of the matrix
print("Determinant:")
print(determinant)

# Print the inverse of the matrix
print("Inverse:")
print(inverse)

# Print the eigenvalues of the matrix
print("Eigenvalues:")
print(eigenvalues)

# Print the eigenvectors of the matrix
print("Eigenvectors:")
print(eigenvectors)

Output:

Matrix:
[[4 2]
 [3 1]]
Determinant:
-2.0
Inverse:
[[-0.5  1. ]
 [ 1.5 -2. ]]
Eigenvalues:
[ 5.37228132+0.j -0.37228132+0.j]
Eigenvectors:
[[ 0.82456484 -0.41597356]
 [ 0.56576746  0.90937671]]

Explanation:

  • Import necessary libraries:
    • Import NumPy and SciPy's linalg module for linear algebra functions.
  • Create a NumPy array (matrix):
    • Define a 2x2 matrix.
  • Find the determinant of the matrix:
    • Use SciPy's det function to compute the determinant.
  • Find the inverse of the matrix:
    • Use SciPy's inv function to compute the inverse.
  • Find the eigenvalues and eigenvectors of the matrix:
    • Use SciPy's eig function to compute the eigenvalues and eigenvectors.
  • Print the matrix:
    • Display the original matrix.
  • Print the determinant of the matrix:
    • Display the determinant.
  • Print the inverse of the matrix:
    • Display the inverse.
  • Print the eigenvalues of the matrix:
    • Display the eigenvalues.
  • Print the eigenvectors of the matrix: Display the eigenvectors.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Interpolate data points using NumPy and SciPy's Interpolate module.
Next: Create Structured array with nested fields in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.