w3resource

Compute Eigenvalues and Eigenvectors of a 4x4 Random array using NumPy


Eigenvalues and Eigenvectors:

Eigenvalues are scalars that indicate how much eigenvectors are stretched or compressed during a linear transformation. Eigenvectors are non-zero vectors that change only in magnitude (not direction) when a linear transformation is applied.

Together, eigenvalues and eigenvectors are critical in solving linear equation systems, performing matrix decompositions, and analyzing stability in dynamic systems.

Write a NumPy program to create a 4x4 array with random values and compute the eigenvalues and eigenvectors.

The task is to write a NumPy program that creates a 4x4 array filled with random values and computes its eigenvalues and eigenvectors. Eigenvalues and eigenvectors are fundamental in various scientific computations, providing insights into the properties of matrices and systems represented by these matrices.

Sample Solution:

Python Code:

# Importing the necessary NumPy library
import numpy as np

# Create a 4x4 array with random values
array = np.random.rand(4, 4)

# Compute the eigenvalues and eigenvectors of the array
eigenvalues, eigenvectors = np.linalg.eig(array)

# Printing the array, eigenvalues, and eigenvectors
print("Array:\n", array)
print("Eigenvalues:\n", eigenvalues)
print("Eigenvectors:\n", eigenvectors)

Output:

Array:
 [[0.19262194 0.51916894 0.42074099 0.01309212]
 [0.06277975 0.48976393 0.9317715  0.6847245 ]
 [0.10534367 0.44892305 0.89487763 0.55058812]
 [0.61185011 0.63000131 0.63008837 0.62664161]]
Eigenvalues:
 [2.07446976+0.j         0.02717159+0.37218944j 0.02717159-0.37218944j
 0.07509217+0.j        ]
Eigenvectors:
 [[-0.27461381+0.j          0.66451899+0.j          0.66451899-0.j
   0.40410005+0.j        ]
 [-0.5651456 +0.j         -0.19232622+0.32286514j -0.19232622-0.32286514j
  -0.53666598+0.j        ]
 [-0.5127032 +0.j         -0.02159434+0.20830108j -0.02159434-0.20830108j
   0.56426484+0.j        ]
 [-0.58509242+0.j         -0.07710503-0.60612077j -0.07710503+0.60612077j
  -0.4798937 +0.j        ]]

Explanation:

  • Import NumPy library: This step imports the NumPy library, which is essential for numerical operations.
  • Create a 4x4 array: We use np.random.rand(4, 4) to generate a 4x4 matrix with random values between 0 and 1.
  • Compute eigenvalues and eigenvectors: The np.linalg.eig function calculates the eigenvalues and eigenvectors of the given array.
  • Print results: This step prints the original array, its eigenvalues, and eigenvectors.

Python-Numpy Code Editor: