w3resource

NumPy: Compute the sum of the diagonal element of a given array

NumPy: Linear Algebra Exercise-15 with Solution

Write a NumPy program to compute the sum of the diagonal element of a given array.

Sample Solution:

Python Code :

# Importing the NumPy library
import numpy as np

# Create a 2x3 NumPy array 'm' using arange() and reshape()
m = np.arange(6).reshape(2, 3)

# Display the original matrix 'm'
print("Original matrix:")
print(m)

# Calculate the trace of the matrix 'm' using np.trace() function
result = np.trace(m)

# Display the trace of the matrix 'm'
print("Trace of the said matrix:")
print(result)

Sample Output:

Original matrix:
[[0 1 2]
 [3 4 5]]
Condition number of the said matrix:
4

Explanation:

In the above code –

m = np.arange(6).reshape(2,3): This line creates a 2x3 NumPy array m with elements from 0 to 5.

result = np.trace(m): This line attempts to compute the trace of the matrix m. However, it is important to note that the trace of a matrix is defined only for square matrices (i.e., matrices with the same number of rows and columns).

In this case, m is not a square matrix, so the trace is not properly defined. The numpy.trace function will still return a result, but it will only sum the diagonal elements that exist in the non-square matrix. In this case, the trace is the sum of the elements at indices (0, 0) and (1, 1), which is 0 + 4 = 4.

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute the condition number of a given matrix.
Next: Write a NumPy program to get the lower-triangular L in the Cholesky decomposition of a given array.

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/linear-algebra/numpy-linear-algebra-exercise-15.php