Diagonalization of Matrices with NumPy
Introduction to Diagonalization and NumPy
In this lesson, we will explore the diagonalization of matrices using NumPy. Diagonalization is a powerful technique that allows us to simplify complex matrix operations by converting a matrix into a diagonal form — but don't worry, we aren't covering the intricate mathematics behind it. Instead, we'll show you how to use NumPy to achieve this.
Quick Recap: Eigenvalues and Eigenvectors
As you may remember from the previous lesson, eigenvalues and eigenvectors play a crucial role in diagonalizing matrices. In simple terms, when you multiply a matrix by one of its eigenvectors, the result is just the eigenvector multiplied by a corresponding scalar value known as the eigenvalue. This property forms the backbone of the diagonalization process.
It's important to recall that the NumPy function np.linalg.eig() is used to compute eigenvalues and eigenvectors of a square matrix. We'll use this function extensively in the upcoming example, so having this context will be helpful.
Calculate Eigenvalues and Eigenvectors
Let's explore the steps to diagonalize a matrix using NumPy. First, let's calculate the eigenvalues and eigenvectors.
-
Defining a Square Matrix:
- A 2x2 matrix is defined using
np.array. This matrix is used as the input for diagonalization:matrix = np.array([[4, 1], [2, 3]]).
- A 2x2 matrix is defined using
-
Calculating Eigenvalues and Eigenvectors:
- The NumPy function
np.linalg.eig(matrix)calculates the eigenvalues and eigenvectors of the matrix:eigenvalues, eigenvectors = np.linalg.eig(matrix). - Eigenvalues will be used to form the diagonal matrix, and eigenvectors will assist in reconstructing the original matrix.
- The NumPy function
Form a Diagonal Matrix
Now, let's form the diagonal matrix with eigenvalues.
- A diagonal matrix is created using the eigenvalues with
np.diag(eigenvalues):diagonal_matrix = np.diag(eigenvalues). - This matrix contains the eigenvalues on its diagonal, with all other entries being zero.
