How to compute eigen values and eigen vectors in Python

In this python tutorial, we will write a code in Python on how to compute eigenvalues and vectors.

Creation of a Square Matrix in Python

First, we will create a square matrix of order 3X3 using numpy library.

Numpy is a Python library which provides various routines for operations on arrays such as mathematical, logical, shape manipulation and many more.

To know more about the numpy library refer the following link:

Numpy Documentation

 

import numpy as np
a=np.array([[1,2,3],[4,5,6],[7,8,9]])

To print the created matrix use the print function.



print(a)

 

Output:

[[1 2 3]
 [4 5 6]
 [7 8 9]]


Computation of Eigen Values and Eigen Vectors

After creating a square matrix using numpy library we have to use a package in this library known as numpy.linalg. This library is used for calculating all the linear algebra functions like vector products matrix operations(inverse, transpose).

To know more about this library refer the following link

https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.linalg.html

In this library, we have to import the function known as eig to compute eigenvalues and vectors.

from numpy.linalg import eig
values , vectors = eig(a)
print(values)
print(vectors)

Output  1:

Eigenvalues

[ 1.61168440e+01 -1.11684397e+00 -1.30367773e-15]

Output 2:

Eigenvectors

[[-0.23197069 -0.78583024  0.40824829]
 [-0.52532209 -0.08675134 -0.81649658]
 [-0.8186735   0.61232756  0.40824829]]

 

 

Using this function and this package we can compute eigenvectors and eigenvalues for any square matrix of order nXn.

Example-2:

from numpy.linalg import eig
import numpy as np
a=np.array([[10,20,30,40],[1,2,3,5],[7,8,9,10],[15,25,35,45]])
values , vectors = eig(a)
print(values)
print(vectors)

Output 1:

Eigen Values

[ 6.96947758e+01 -3.22806629e+00 -4.66709488e-01 -3.59740472e-14]

Output 2:

Eigen Vectors

[[-6.28224280e-01 -7.67762260e-01 -5.75701703e-01 -4.08248290e-01]
 [-7.35387665e-02 -1.62230993e-02  7.06561093e-01  8.16496581e-01]
 [-2.05200662e-01  6.09975078e-01  2.05319101e-01 -4.08248290e-01]
 [-7.46872808e-01 -1.95469507e-01 -3.56627310e-01 -2.73218204e-14]]

The above output is an example of a square matrix of order 4X4.

You can also read,

One response to “How to compute eigen values and eigen vectors in Python”

  1. Sinister says:

    Thank you for the information. !

Leave a Reply

Your email address will not be published. Required fields are marked *