Java Program to Find the Normal and Trace of a Matrix

Last Updated : 20 Aug, 2026

The trace and normal are two important properties of a matrix. The trace is calculated using the main diagonal elements, while the normal is calculated using all elements of the matrix.

Example

Input: {{1, 4, 4}, {2, 3, 7}, {0, 5, 1}}
Output: Trace = 5, Normal = 11

Input: {{8, 9, 11}, {0, 1, 15}, {4, 10, -7}}
Output: Trace = 2, Normal = 25

Trace of a Matrix

The trace of a square matrix is the sum of all elements on its main diagonal.

Example:

1 2 3
4 5 6
7 8 9

Trace = 1 + 5 + 9 = 15

Normal of a Matrix

The normal (Frobenius norm) of a matrix is the square root of the sum of the squares of all its elements.

Example:

1 2
3 4

Normal = √(1² + 2² + 3² + 4²) = √30

Example: Program to Find Normal and Trace

Java
public class Geeks {

    // Method to calculate the normal
    static double findNormal(int[][] matrix) {
        int sum = 0;

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                sum += matrix[i][j] * matrix[i][j];
            }
        }

        return Math.sqrt(sum);
    }

    // Method to calculate the trace
    static int findTrace(int[][] matrix) {
        int sum = 0;

        for (int i = 0; i < matrix.length; i++) {
            sum += matrix[i][i];
        }

        return sum;
    }

    public static void main(String[] args) {

        int[][] matrix = {
            {1, 4, 4},
            {2, 3, 7},
            {0, 5, 1}
        };

        System.out.println("Trace of the Matrix: "
                           + findTrace(matrix));

        System.out.println("Normal of the Matrix: "
                           + findNormal(matrix));
    }
}

Output
Trace of the Matrix: 5
Normal of the Matrix: 11.0

Explanation:

  • findTrace() adds the elements on the main diagonal.
  • findNormal() squares and adds every element of the matrix.
  • Math.sqrt() calculates the square root to obtain the normal.
  • The trace is defined only for a square matrix, while the Frobenius normal can also be calculated for a rectangular matrix.
Comment