Finding the eigenvalues and eigenvectors of a matrix

The Python library NumPy provides the function eig() through the linalg module. The eig() function returns the eigenvalues and the eigenvectors of a square matrix.

Linear Algebra Updated 22 Mar 2025 1 min read

Overview

  • The function eig() from the linalg module of NumPy library computes the eigenvalues and eigenvectors of a given square matrix.

Example

python
# Example Python program that finds the eigenvectors and eigenvalues

            # of a given square matrix using the function eig() of linalg module from

            # the NumPy library

            import numpy

# Printing format of floating point numbers

            numpy.set_printoptions(suppress=True, formatter={'float_kind':'{:0.2f}'.format})

# Generate matrix elements

            elems = numpy.arange(-15, 16, 2)

# Create matrix

            matrix  = elems.reshape(4, 4)

            print("A 4x4 matrix:")

            print(matrix)

# Find the eigen values and eigen vectors of the matrix

            results = numpy.linalg.eig(matrix)

print("Eigenvalues:")

            print(results.eigenvalues)

print("Eigenvectors:")

            print(results.eigenvectors)

Output

Output
A 4x4 matrix:

[[-15 -13 -11  -9]

 [ -7  -5  -3  -1]

 [  1   3   5   7]

 [  9  11  13  15]]

Eigenvalues:

[-17.89 0.00 17.89 -0.00]

Eigenvectors:

[[0.82 0.55 0.38 -0.43]

 [0.42 -0.73 -0.02 0.83]

 [0.02 -0.18 -0.42 -0.35]

 [-0.38 0.37 -0.82 -0.04]]