How to calculate the normal and trace of square matrix in Java

1 Answer

0 votes
public class MyClass {
    private static double CalculateNormal(int[][] matrix) {
	    int normal = 0;

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

	    return Math.sqrt(normal);
    }

    private static int CalculateTrace(int[][] matrix) {
	    int trace = 0;

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

	    return trace;
    }

    public static void main(String args[]) {
     	int[][] matrix =
        	    {
        		    {1, 1, 1, 1, 1},
        		    {2, 2, 2, 2, 2},
        		    {3, 3, 3, 3, 3},
        		    {4, 4, 4, 4, 4},
        		    {5, 5, 5, 5, 5}
        	    };

	    System.out.println(CalculateTrace(matrix));

	    System.out.println(CalculateNormal(matrix));
    }
}





/*
run:
 
15
16.583123951777
 
*/

 



answered Feb 27, 2023 by avibootz
edited Feb 27, 2023 by avibootz

Related questions

1 answer 126 views
1 answer 175 views
1 answer 133 views
1 answer 138 views
1 answer 130 views
...