How to Find Eigenvectors Using NumPy in Python
Use
numpy.linalg.eig to find eigenvectors and eigenvalues of a square matrix. It returns two arrays: one for eigenvalues and one for eigenvectors, where each column in the eigenvector array corresponds to an eigenvector.Syntax
The function to find eigenvectors in NumPy is numpy.linalg.eig. It takes a square matrix as input and returns two outputs:
w: an array of eigenvalues.v: a 2D array where each column is an eigenvector corresponding to the eigenvalue inw.
python
w, v = numpy.linalg.eig(a)
Example
This example shows how to find eigenvalues and eigenvectors of a 2x2 matrix using NumPy.
python
import numpy as np # Define a 2x2 matrix a = np.array([[4, 2], [1, 3]]) # Calculate eigenvalues and eigenvectors w, v = np.linalg.eig(a) print("Eigenvalues:", w) print("Eigenvectors:") print(v)
Output
Eigenvalues: [5. 2.]
Eigenvectors:
[[ 0.89442719 -0.70710678]
[ 0.4472136 0.70710678]]
Common Pitfalls
Common mistakes when finding eigenvectors with NumPy include:
- Passing a non-square matrix, which causes an error because eigenvectors are defined only for square matrices.
- Confusing rows and columns in the eigenvector output; each column of the returned matrix is an eigenvector, not each row.
- Not normalizing eigenvectors if needed, as NumPy returns normalized eigenvectors by default.
python
import numpy as np # Wrong: Non-square matrix try: a = np.array([[1, 2, 3], [4, 5, 6]]) w, v = np.linalg.eig(a) except np.linalg.LinAlgError as e: print("Error:", e) # Correct: Square matrix b = np.array([[1, 2], [3, 4]]) w, v = np.linalg.eig(b) print("Eigenvalues:", w) print("Eigenvectors (columns):") print(v)
Output
Error: Last 2 dimensions of the array must be square
Eigenvalues: [ 5.37228132 -0.37228132]
Eigenvectors (columns):
[[-0.82456484 -0.41597356]
[-0.56576746 0.90937671]]
Quick Reference
Summary tips for finding eigenvectors with NumPy:
- Use
numpy.linalg.eigwith a square matrix. - Eigenvalues are returned as a 1D array.
- Eigenvectors are columns in the 2D array output.
- Eigenvectors are normalized by default.
- Check matrix shape before calling to avoid errors.
Key Takeaways
Use numpy.linalg.eig to get eigenvalues and eigenvectors of a square matrix.
Eigenvectors are returned as columns in the second output array.
Input matrix must be square to avoid errors.
Eigenvectors from NumPy are normalized by default.
Check matrix shape and understand output structure to avoid confusion.