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
, to zero.for
loop.
trace
variable.Note: Diagonal elements have row numbers equal to the column numbers.
trace
value.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); } }
RELATED TAGS
CONTRIBUTOR
View all Courses