How to Diagonalize a matrix in Python using NumPy

Diagonalization is a process where you find a diagonal matrix that is similar to a given square matrix. The numpy package allows you to diagonalize a matrix in Python using NumPy using steps.

Steps to Diagonalize a matrix in Python using NumPy

Below are the steps to diagonalize a matrix using NumPy in Python.

Step 1: Import NumPy

Import the most required library using the import statement .

import numpy as np

Step 2: Define the Matrix

Replace the A array with the matrix you want to diagonalize. You can create a numpy array using the np.array() function.

A = np.array([[20, 10],
              [10, 30]])

Step 3: Find Eigenvalues and Eigenvectors

Calculate the eigenvalues and eigenvectors for the matrix you have created in the step 2.

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

Step 4: Check Diagonalizability

Check the values of all eigenvalues are real. If there are complex eigenvalues, the matrix is not diagonalizable over the real numbers.

if not np.all(np.iscomplex(eigenvalues)):

Step 5: Create Diagonal Matrix (D)

    D = np.diag(eigenvalues)

Step 6: Find the Inverse of Eigenvector Matrix (P_inv)

    P_inv = np.linalg.inv(eigenvectors)

Step 7: Diagonalize the Matrix

Use the formula ( P^{-1}AP = D ) to compute the diagonalized matrix.

    diagonalized_matrix = np.dot(P_inv, np.dot(A, eigenvectors))

Step 8: Print Diagonalized Matrix

    print("Diagonalized Matrix:")
    print(diagonalized_matrix)
else:
    print("Matrix is not diagonalizable.")

Full Code

import numpy as np

# Step 1: Define your matrix
A = np.array([[20, 10],
              [10, 30]])
# Step 2: Find eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(A)

# Step 3: Check if the matrix is diagonalizable
if not np.all(np.iscomplex(eigenvalues)):
    # Step 4: Create the diagonal matrix
    D = np.diag(eigenvalues)

    # Step 5: Find the inverse of the eigenvector matrix
    P_inv = np.linalg.inv(eigenvectors)

    # Step 6: Diagonalize the matrix
    diagonalized_matrix = np.dot(P_inv, np.dot(A, eigenvectors))

    # Print the diagonalized matrix
    print("Diagonalized Matrix:")
    print(diagonalized_matrix)
else:
    print("Matrix is not diagonalizable.")

Output

Diagonalized Matrix:
[[ 1.38196601e+01  1.54583004e-15]
 [-4.86193050e-16  3.61803399e+01]]

Conclusion

You can easily find whether the matrix is diagonable or not using the Eigenvalues and Eigenvectors. The above steps will allow you to diagonalize a matrix in Python using NumPy.Replace the matrix A with your specific matrix, and these steps should help you diagonalize it using NumPy in Python.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link