w3resource

Calculate the Trace of a 5x5 random array using NumPy

NumPy: Advanced Exercise-20 with Solution

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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Flattening a 3x3x3 array to a 1D array using NumPy.
Next: Extract the uper triangular part of a 4x4 random array using NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/advanced-numpy-exercise-20.php