Compute the trace of a square matrix, defined as the sum of its diagonal elements.
Trace of Matrix A:
tr(A)=i=1∑naiiwhere aii are the diagonal elements of matrix AA.
A: 2D NumPy array, shape (N, N) - square matrixInput: A = [[1, 2], [3, 4]]
Output: 5
Input: A = [[2, -1, 0], [3, 5, 1], [0, 2, -2]]
Output: 5 (trace = 2 + 5 + (-2))
Input: A = [[42]]
Output: 42
Use a loop to iterate through indices and accumulate A[i, i] for each diagonal element.
The number of diagonal elements equals A.shape[0] (or A.shape[1] for square matrices).
np.trace() or A.diagonal().sum()Sign in to take notes on this problem
Accepts: array
Compute the trace of a square matrix, defined as the sum of its diagonal elements.
Trace of Matrix A:
tr(A)=i=1∑naiiwhere aii are the diagonal elements of matrix AA.
A: 2D NumPy array, shape (N, N) - square matrixInput: A = [[1, 2], [3, 4]]
Output: 5
Input: A = [[2, -1, 0], [3, 5, 1], [0, 2, -2]]
Output: 5 (trace = 2 + 5 + (-2))
Input: A = [[42]]
Output: 42
Use a loop to iterate through indices and accumulate A[i, i] for each diagonal element.
The number of diagonal elements equals A.shape[0] (or A.shape[1] for square matrices).
np.trace() or A.diagonal().sum()Sign in to take notes on this problem
Accepts: array