How to find the trace of a matrix

What is the trace of a matrix?

The sum of the principal diagonal elements is called the trace of the matrix.

For example, consider the following 2x2 matrix.

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

The trace of the matrix above is as follows:

1 + 5 + 9 = 15

Trace - 1 + 5 + 9 = 15

Algorithm

  1. Initialise a variable, i.e., trace, to zero.
  2. Iterate through the elements of the principal diagonal elements with the help of a for loop.
    1. Add the diagonal element to the trace variable.

Note: Diagonal elements have row numbers equal to the column numbers.

  1. Return the trace value.
  • Time complexity - O(N)
  • Space complexity - O(1)

Example

import java.util.Arrays;
public class Main{
private static int computeTrace(int[][] matrix){
int trace = 0;
// Run a loop iterating the diagonal elements
for (int i = 0; i < matrix.length; i++){
// diagonal elements have row number = column number
trace += matrix[i][i];
}
return trace;
}
private static void printMatrix(int[][] matrix){
for (int[] row : matrix)
System.out.println(Arrays.toString(row));
}
public static void main(String[] args){
int matrix[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8 , 9}
};
int trace = computeTrace(matrix);
printMatrix(matrix);
System.out.println("Trace of the above matrix is " + trace);
}
}
Trace of Matrix

Free Resources