0
0
NumPydata~5 mins

np.linalg.eig() for eigenvalues in NumPy

Choose your learning style9 modes available
Introduction

We use np.linalg.eig() to find special numbers called eigenvalues and vectors from a square matrix. These help us understand important properties of the matrix.

When you want to find the main directions of data in machine learning.
To analyze stability in systems like weather or economics.
When solving physics problems involving vibrations or rotations.
To reduce data dimensions while keeping important information.
When studying graphs or networks to find key nodes.
Syntax
NumPy
eigenvalues, eigenvectors = np.linalg.eig(matrix)

matrix must be a square 2D numpy array.

The function returns two arrays: eigenvalues (1D) and eigenvectors (2D).

Examples
Find eigenvalues and eigenvectors of a simple diagonal matrix.
NumPy
import numpy as np
A = np.array([[2, 0], [0, 3]])
vals, vecs = np.linalg.eig(A)
Calculate eigenvalues and eigenvectors for a non-diagonal matrix.
NumPy
B = np.array([[4, 1], [2, 3]])
vals, vecs = np.linalg.eig(B)
Example with symmetric matrix to see real eigenvalues.
NumPy
C = np.array([[1, 2], [2, 1]])
vals, vecs = np.linalg.eig(C)
Sample Program

This program finds eigenvalues and eigenvectors of a 2x2 matrix. It prints both so you can see the special numbers and directions.

NumPy
import numpy as np

# Define a 2x2 matrix
matrix = np.array([[5, 4], [1, 2]])

# Calculate eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(matrix)

print("Eigenvalues:")
print(eigenvalues)
print("\nEigenvectors:")
print(eigenvectors)
OutputSuccess
Important Notes

Eigenvalues can be complex numbers if the matrix is not symmetric.

Eigenvectors are normalized to length 1 by default.

Order of eigenvalues matches the columns of eigenvectors.

Summary

np.linalg.eig() finds eigenvalues and eigenvectors of square matrices.

Eigenvalues tell you about scaling factors; eigenvectors show directions.

This is useful in many fields like data science, physics, and engineering.