NumPy: Compute the sum of the diagonal element of a given array
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics