The Trace: Summing Down the Diagonal

Linear AlgebraEasy+10 XP+10

The Trace: Summing Down the Diagonal

The trace of a square matrix is the sum of the numbers running down its main diagonal — top-left to bottom-right. Everything off that diagonal is ignored completely.

Task: write trace(matrix) returning that sum.

  • matrix is a list of rows and is always square, so it has as many rows as columns.
  • The main diagonal is the entries where the row number equals the column number: matrix[0][0], matrix[1][1], matrix[2][2], and so on.
  • Don't round. Return the sum exactly as the arithmetic gives it — an integer in, an integer out.

It looks like an arbitrary thing to add up, and it isn't. The trace equals the sum of the matrix's eigenvalues, which means you can read that total straight off the diagonal without computing a single eigenvalue. It also survives a change of basis untouched, which is why it shows up everywhere from physics to the gradient formulas behind neural networks.

Examples

matrix = [[1, 2], [3, 4]]
returns 5
matrix = [[2, 9, 9], [9, 3, 9], [9, 9, 4]]
returns 9

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run