Click4Ai

28.

Easy

Write a function matrix_trace(matrix) that computes the trace of a square matrix. The trace is the sum of all diagonal elements. Do not use np.trace().

Example:

Input: matrix = [[1, 2, 3],

[4, 5, 6],

[7, 8, 9]]

Output: 15

**Explanation:** Trace = 1 + 5 + 9 = 15

Constraints:

  • Matrix is always square (n×n)
  • 1 <= n <= 100
  • Return an integer
  • Test Cases

    Test Case 1
    Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    Expected: 15
    Test Case 2
    Input: [[1, 0], [0, 1]]
    Expected: 2
    Test Case 3
    Input: [[5]]
    Expected: 5
    + 2 hidden test cases