w3resource

Calculate the Trace of a 5x5 random array using NumPy


Write a NumPy program to create a 5x5 array with random values and calculate the trace of the matrix.

The task involves creating a 5x5 array filled with random values using NumPy and calculating its trace. The trace of a matrix is the sum of the elements on the main diagonal, which provides valuable information in various mathematical and engineering applications.

Sample Solution:

Python Code:

# Importing the necessary NumPy library
import numpy as np

# Create a 5x5 array with random values
array = np.random.rand(5, 5)

# Calculate the trace of the matrix (sum of diagonal elements)
trace = np.trace(array)

# Printing the array and its trace
print("5x5 Array:\n", array)
print("Trace of the array:\n", trace)

Output:

5x5 Array:
 [[0.59843688 0.77748991 0.65775131 0.59554826 0.32333545]
 [0.35356751 0.4451821  0.92174646 0.83957701 0.08239685]
 [0.9434021  0.59178038 0.61280957 0.28534012 0.81434316]
 [0.43013274 0.46585557 0.10540968 0.2159182  0.37533754]
 [0.27162629 0.99241093 0.09860645 0.71335411 0.59528253]]
Trace of the array:
 2.4676292803171025

Explanation:

  • Import NumPy library: This step imports the NumPy library, which is essential for numerical operations.
  • Create a 5x5 array: We use np.random.rand(5, 5) to generate a 5x5 matrix with random values between 0 and 1.
  • Calculate the trace of the matrix: The np.trace function calculates the trace of the matrix, which is the sum of its diagonal elements.
  • Print results: This step prints the original array and its trace.

Python-Numpy Code Editor: