Trusted answers to developer questions

abhilash

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

- Initialise a variable, i.e.,
`trace`

, to zero. - Iterate through the elements of the principal diagonal elements with the help of a
`for`

loop.- Add the diagonal element to the
`trace`

variable.

- Add the diagonal element to the

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

- Return the
`trace`

value.

- Time complexity - O(N)
- Space complexity - O(1)

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

RELATED TAGS

matrix

communitycreator

CONTRIBUTOR

abhilash

RELATED COURSES

View all Courses

Keep Exploring

Related Courses