Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Compute the eigenvalues of a complex Hermitian or real symmetric matrix in Python
To compute the eigenvalues of a complex Hermitian or real symmetric matrix, use the numpy.linalg.eigvalsh() method. This function returns eigenvalues in ascending order, each repeated according to its multiplicity.
Parameters
The eigvalsh() function accepts these parameters ?
- a: A complex Hermitian or real symmetric matrix whose eigenvalues are to be computed
- UPLO: Specifies whether to use the lower triangular part ('L', default) or upper triangular part ('U'). Only the real parts of the diagonal are considered to preserve the Hermitian property
Example with Complex Hermitian Matrix
Let's create a complex Hermitian matrix and compute its eigenvalues ?
import numpy as np
from numpy import linalg as LA
# Create a complex Hermitian matrix
arr = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
# Display the matrix
print("Our Matrix:")
print(arr)
print(f"\nDimensions: {arr.ndim}")
print(f"Datatype: {arr.dtype}")
print(f"Shape: {arr.shape}")
# Compute eigenvalues
eigenvalues = LA.eigvalsh(arr)
print(f"\nEigenvalues: {eigenvalues}")
Our Matrix: [[5.+2.j 9.-2.j] [0.+2.j 2.-1.j]] Dimensions: 2 Datatype: complex128 Shape: (2, 2) Eigenvalues: [1. 6.]
Example with Real Symmetric Matrix
The function also works with real symmetric matrices ?
import numpy as np
from numpy import linalg as LA
# Create a real symmetric matrix
real_matrix = np.array([[4, 2, 1],
[2, 5, 3],
[1, 3, 6]])
print("Real Symmetric Matrix:")
print(real_matrix)
# Compute eigenvalues
eigenvalues = LA.eigvalsh(real_matrix)
print(f"\nEigenvalues: {eigenvalues}")
Real Symmetric Matrix: [[4 2 1] [2 5 3] [1 3 6]] Eigenvalues: [1.17157288 4. 9.82842712]
Using UPLO Parameter
You can specify which triangular part to use for computation ?
import numpy as np
from numpy import linalg as LA
matrix = np.array([[3, 1], [1, 2]])
# Using lower triangular (default)
eigenvals_lower = LA.eigvalsh(matrix, UPLO='L')
# Using upper triangular
eigenvals_upper = LA.eigvalsh(matrix, UPLO='U')
print(f"Lower triangular: {eigenvals_lower}")
print(f"Upper triangular: {eigenvals_upper}")
Lower triangular: [1.38196601 3.61803399] Upper triangular: [1.38196601 3.61803399]
Key Points
- Returns eigenvalues in ascending order
- Works with both complex Hermitian and real symmetric matrices
- Only real parts of diagonal elements are used for Hermitian matrices
- More efficient than
numpy.linalg.eig()when you only need eigenvalues
Conclusion
Use numpy.linalg.eigvalsh() to efficiently compute eigenvalues of Hermitian or symmetric matrices. The function returns eigenvalues in ascending order and handles both complex and real matrices appropriately.
Advertisements
