How to Sort Eigenvalues and Eigenvectors in Python?

Estimated read time 2 min read

To sort eigenvalues and eigenvectors in Python, you can use the numpy library’s linalg.eig() function, which computes the eigenvalues and eigenvectors of a given matrix.

Here’s an example implementation:

import numpy as np

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

# Compute the eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(A)

# Sort the eigenvalues and corresponding eigenvectors in descending order
idx = eigenvalues.argsort()[::-1]
eigenvalues = eigenvalues[idx]
eigenvectors = eigenvectors[:, idx]

# Print the sorted eigenvalues and eigenvectors
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:", eigenvectors)

In this example, we define a 2×2 matrix A, and compute its eigenvalues and eigenvectors using the linalg.eig() function. We then use the argsort() function to obtain the indices that would sort the eigenvalues in ascending order. We reverse the order of the indices using the [::-1] slice to sort the eigenvalues in descending order. We use the sorted indices to sort the corresponding eigenvectors as well. Finally, we print the sorted eigenvalues and eigenvectors.

Note that the eigenvalues and eigenvectors are sorted according to the magnitude of the eigenvalues. If you want to sort the eigenvalues in a different order or based on a different criterion, you can modify the argsort() function accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply