Problems
Loading...
1 / 1

Matrix Trace

Linear Algebra
Easy

Compute the trace of a square matrix, defined as the sum of its diagonal elements.

Mathematical Definition

Trace of Matrix A:

tr(A)=i=1naii\operatorname{tr}(A) = \sum_{i=1}^{n} a_{ii}

where aii are the diagonal elements of matrix AA.

Function Arguments

  • A: 2D NumPy array, shape (N, N) - square matrix
Loading visualization...

Examples

Input: 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

Hint 1

Use a loop to iterate through indices and accumulate A[i, i] for each diagonal element.

Hint 2

The number of diagonal elements equals A.shape[0] (or A.shape[1] for square matrices).

Requirements

  • Return a single scalar (float or int)
  • Do not use np.trace() or A.diagonal().sum()
  • Compute manually via indexing or iteration
  • Handle negative, zero, and float elements
  • Handle 1x1 edge case

Constraints

  • 1 ≤ N ≤ 1000
  • Matrix elements can be any float or int
  • Time limit: 100ms
Try Similar Problems