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):ais a square 2D array (matrix).- Returns: (
w,v) wherewis eigenvalues array,vis 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
| Function | Description |
|---|---|
| numpy.linalg.eig(a) | Returns eigenvalues and eigenvectors of square matrix a |
| a | Square 2D NumPy array (matrix) |
| Returns | Tuple (eigenvalues array, eigenvectors matrix) |
| Eigenvalues | 1D array of eigenvalues |
| Eigenvectors | 2D 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.