# Compute the eigenvalues of a complex Hermitian or real symmetric matrix in Python

PythonNumpyServer Side ProgrammingProgramming

To compute the eigenvalues of a complex Hermitian or real symmetric matrix, use the numpy.eigvalsh() method. The method returns the eigenvalues in ascending order, each repeated according to its multiplicity.

The 1st parameter, a is a complex- or real-valued matrix whose eigenvalues are to be computed. The 2nd parameter, UPLO specifies whether the calculation is done with the lower triangular part of a (‘L’, default) or the upper triangular part (‘U’). Irrespective of this value only the real parts of the diagonal will be considered in the computation to preserve the notion of a Hermitian matrix. It therefore follows that the imaginary part of the diagonal will always be treated as zero.

## Steps

At first, import the required libraries -

import numpy as np
from numpy import linalg as LA

Creating a 2D numpy array using the numpy.array() method −

arr = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])


Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)


Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

Get the Shape −

print("\nShape of our Array object...\n",arr.shape)


To compute the eigenvalues of a complex Hermitian or real symmetric matrix, use the numpy.eigvalsh() method −

print("\nResult...\n",LA.eigvalsh(arr))

## Example

from numpy import linalg as LA
import numpy as np

# Creating a 2D numpy array using the numpy.array() method
arr = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To compute the eigenvalues of a complex Hermitian or real symmetric matrix, use the numpy.eigvalsh() method
print("\nResult...\n",LA.eigvalsh(arr))

## Output

Our Array...
[[5.+2.j 9.-2.j]
[0.+2.j 2.-1.j]]

Dimensions of our Array...
2

Datatype of our Array object...
complex128

Shape of our Array object...
(2, 2)

Result...
[1. 6.]
Updated on 24-Feb-2022 13:03:48