0
0
NumpyHow-ToBeginner ยท 3 min read

How to Find Eigenvalues Using NumPy in Python

Use numpy.linalg.eig to find eigenvalues of a square matrix in NumPy. It returns a tuple where the first element contains the eigenvalues as a 1D array.
๐Ÿ“

Syntax

The function to find eigenvalues in NumPy is numpy.linalg.eig. It takes a square matrix as input and returns two arrays: the first contains eigenvalues, and the second contains eigenvectors.

  • numpy.linalg.eig(a): a is a square 2D array (matrix).
  • Returns: (w, v) where w is eigenvalues array, v is eigenvectors matrix.
python
import numpy as np

w, v = np.linalg.eig(a)
๐Ÿ’ป

Example

This example shows how to find eigenvalues of a 2x2 matrix using numpy.linalg.eig. It prints the eigenvalues and eigenvectors.

python
import numpy as np

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

# Calculate eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(matrix)

print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)
Output
Eigenvalues: [5. 2.] Eigenvectors: [[ 0.89442719 -0.70710678] [ 0.4472136 0.70710678]]
โš ๏ธ

Common Pitfalls

Common mistakes when finding eigenvalues with NumPy include:

  • Passing a non-square matrix, which causes an error.
  • Confusing eigenvalues with eigenvectors; eigenvalues are returned as a 1D array, eigenvectors as columns of a 2D array.
  • Not handling complex eigenvalues that can appear for some matrices.

Example of wrong input and correct usage:

python
import numpy as np

# Wrong: Non-square matrix
try:
    np.linalg.eig(np.array([[1, 2, 3], [4, 5, 6]]))
except np.linalg.LinAlgError as e:
    print("Error:", e)

# Right: Square matrix
matrix = np.array([[1, 2], [3, 4]])
eigenvalues, _ = np.linalg.eig(matrix)
print("Eigenvalues:", eigenvalues)
Output
Error: Last 2 dimensions of the array must be square Eigenvalues: [-0.37228132 5.37228132]
๐Ÿ“Š

Quick Reference

FunctionDescription
numpy.linalg.eig(a)Returns eigenvalues and eigenvectors of square matrix a
aSquare 2D NumPy array (matrix)
ReturnsTuple (eigenvalues array, eigenvectors matrix)
Eigenvalues1D array of eigenvalues
Eigenvectors2D array with eigenvectors as columns
โœ…

Key Takeaways

Use numpy.linalg.eig to find eigenvalues and eigenvectors of a square matrix.
Input matrix must be square; otherwise, NumPy raises an error.
Eigenvalues are returned as a 1D array; eigenvectors are columns in a 2D array.
Some matrices may have complex eigenvalues; handle them accordingly.
Always check matrix shape before calling the function to avoid errors.