If the transpose of a square matrix is the same as the supplied matrix, then the matrix is symmetric.
For example, consider the matrix below.
[[1, 1, -1],
[1, 2, 0],
[-1, 0, 5]]
The transpose of the matrix is as follows.
[[1, 1, -1],
[1, 2, 0],
[-1, 0, 5]]
Since the transpose of the matrix is the same as the given matrix, the matrix is a symmetric matrix.
import java.util.Arrays;public class Main {private static void printMatrix(int[][] matrix){for(int[] row: matrix){System.out.println(Arrays.toString(row));}}private static int[][] transpose(int[][] matrix){int[][] transpose = new int[matrix[0].length][matrix.length];for(int i = 0;i < matrix.length; i++) for(int j = 0; j < matrix[0].length; j++) transpose[j][i] = matrix[i][j];return transpose;}private static boolean checkSymmetricMatrix(int[][] matrix){int[][] result = transpose(matrix);if(result.length != matrix.length || result[0].length != matrix[0].length) return false;for(int i=0;i < matrix.length; i++){for (int j = 0; j < matrix[i].length; j++)if(result[i][j] != matrix[i][j]) return false;}return true;}private static void wrapper(int[][] matrix){printMatrix(matrix);if(checkSymmetricMatrix(matrix)) System.out.println("The matrix is a symmetric matrix");else System.out.println("The matrix is not a symmetric matrix");}public static void main(String[] args){int[][] matrix = {{1, 1, -1},{1, 2, 0},{-1, 0, 5}};wrapper(matrix);System.out.println("-------------");int[][] matrix1 = {{4, 0},{5, -4}};wrapper(matrix1);}}
We can optimize the approach above. Instead of calculating the transpose and then comparing the matrices, we can compare the elements at (i, j)
and (j, i)
. If the elements are not equal, then the matrix is not a symmetric matrix.
import java.util.Arrays;public class Main {private static void printMatrix(int[][] matrix){for(int[] row: matrix){System.out.println(Arrays.toString(row));}}private static boolean checkSymmetricMatrix(int[][] matrix){for(int i=0;i < matrix.length; i++){for (int j = 0; j < matrix[i].length; j++)if(matrix[i][j] != matrix[j][i]) return false;}return true;}private static void wrapper(int[][] matrix){printMatrix(matrix);if(checkSymmetricMatrix(matrix)) System.out.println("The matrix is a symmetric matrix");else System.out.println("The matrix is not a symmetric matrix");}public static void main(String[] args){int[][] matrix = {{1, 1, -1},{1, 2, 0},{-1, 0, 5}};wrapper(matrix);System.out.println("-------------");int[][] matrix1 = {{4, 0},{5, -4}};wrapper(matrix1);}}