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
- Initialise a variable, i.e.,
trace, to zero. - Iterate through the elements of the principal diagonal elements with the help of a
forloop.- Add the diagonal element to the
tracevariable.
- Add the diagonal element to the
Note: Diagonal elements have row numbers equal to the column numbers.
- Return the
tracevalue.
- 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 elementsfor (int i = 0; i < matrix.length; i++){// diagonal elements have row number = column numbertrace += 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