w3resource

NumPy: Compute the eigenvalues and right eigenvectors of a given square array

NumPy: Linear Algebra Exercise-7 with Solution

Write a NumPy program to compute the eigenvalues and right eigenvectors of a given square array.

Sample Solution :

Python Code :

import numpy as np

# Create a matrix 'm' using np.mat() function
m = np.mat("3 -2; 1 0")

# Display the original matrix 'm'
print("Original matrix:")
print("a\n", m)

# Compute the eigenvalues and eigenvectors of the matrix 'm' using np.linalg.eig() function
w, v = np.linalg.eig(m)

# Display the eigenvalues of the said matrix
print("Eigenvalues of the said matrix", w)

# Display the eigenvectors of the said matrix
print("Eigenvectors of the said matrix", v) 

Sample Output:

Original matrix:
a
 [[ 3 -2]
 [ 1  0]]
Eigenvalues of the said matrix [ 2.  1.]
Eigenvectors of the said matrix [[ 0.89442719  0.70710678]
 [ 0.4472136   0.70710678]]

Explanation:

In the above exercise –

m = np.mat("3 -2;1 0"): This line creates a 2x2 NumPy matrix m with the elements:

[[ 3, -2],

[ 1, 0]]

w, v = np.linalg.eig(m): This line computes the eigenvalues and eigenvectors of the matrix m. The eig function takes a square matrix as input and returns two arrays: one containing the eigenvalues, and the other containing the corresponding eigenvectors as columns.

print( "Eigenvalues of the said matrix", w): This line prints the eigenvalues of the matrix m. In this case, the eigenvalues are 2.0 and 1.0.

print( "Eigenvectors of the said matrix", v): This line prints the eigenvectors of the matrix m as columns of the v array. The eigenvectors corresponding to the eigenvalues 2.0 and 1.0 are [[-0.89442719, 0.70710678], [-0.4472136 , -0.70710678]].

Note:

In linear algebra, an eigenvector or characteristic vector of a linear transformation is a nonzero vector that changes at most by a scalar factor when that linear transformation is applied to it. The corresponding eigenvalue, often denoted by λ (lambda), is the factor by which the eigenvector is scaled.

Geometrically, an eigenvector, corresponding to a real nonzero eigenvalue, points in a direction in which it is stretched by the transformation and the eigenvalue is the factor by which it is stretched. If the eigenvalue is negative, the direction is reversed.

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension.
Next: Write a NumPy program to compute the Kronecker product of two given mulitdimension arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/linear-algebra/numpy-linear-algebra-exercise-7.php