Introduction to Eigenvalues and Eigenvectors with NumPy

Introduction to Eigenvalues and Eigenvectors

Welcome to the first lesson of our course on Linear Algebra with NumPy. In this lesson, we will explore the concepts of eigenvalues and eigenvectors. These concepts play a critical role in various fields such as engineering and data science. We'll focus on applying these concepts practically, without delving into the underlying mathematical theory.

By the end of this lesson, you'll be ready to use NumPy to compute eigenvalues and eigenvectors of your matrices. Let's start delving into the process, by breaking it down into clear, manageable steps.

Role of Eigenvalues and Eigenvectors

In linear algebra, eigenvalues and eigenvectors are central to understanding how linear transformations affect vector spaces. Eigenvectors remain in their span (retain their direction) when a transformation is applied, merely being scaled by their corresponding eigenvalue—this scalar factor determines the degree of stretching or compression. This characteristic simplifies the analysis of transformations, allowing complex matrices to be broken down into simpler components. Such decomposition is vital for grasping the core structure of a transformation, helping us to interpret its fundamental behavior without unnecessary complexity.

Step 1: Define a Square Matrix

First, we need to define a square matrix. A square matrix has the same number of rows and columns. Here's how you do it in NumPy:

import numpy as np

# Defining a square matrix
matrix = np.array([[4, 1], [2, 3]])

This code creates a 2x2 matrix with predefined values.

Step 2: Calculate Eigenvalues and Eigenvectors

Next, we use NumPy's np.linalg.eig() function to calculate the eigenvalues and eigenvectors of our matrix:

eigenvalues, eigenvectors = np.linalg.eig(matrix)

This function returns two outputs: eigenvalues and eigenvectors. The eigenvalues represent special scalars associated with the matrix, while the eigenvectors are the vectors associated with these scalars.

Step 3: Display Results

Finally, let's display the results to understand what we've computed:

print("Matrix:\n", matrix)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)

# Output:
# Matrix:
#  [[4 1]
#  [2 3]]
# Eigenvalues: [5. 2.]
# Eigenvectors:
#  [[ 0.70710678 -0.4472136 ]
#  [ 0.70710678  0.89442719]]

The output shows the original matrix, the eigenvalues, and the eigenvectors. Note how each eigenvector corresponds to an eigenvalue.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal