A matrix is called an idempotent matrix if the matrix when multiplied by itself results in the same matrix, i.e., .
The following are some examples of idempotent matrices:
Example 1:
[[0,0],
[0,0]]
Example 2:
[[2, -2, -4],
[-1, 3, 4],
[1, -2, -3]]
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[][] multiplyMatrix(int numRows1, int numCols1, int[][] matrix1, int numRows2, int numCols2, int[][] matrix2) throws Exception {if(numCols1 != numRows2){throw new Exception("Invalid dimensions for matrix multiplication");}int[][] result = new int[numRows1][numCols2];for (int i = 0; i < numRows1; i++) {for (int j = 0; j < numCols2; j++) {for (int k = 0; k < numRows2; k++)result[i][j] += matrix1[i][k] * matrix2[k][j];}}return result;}private static boolean checkIdempotentMatrix(int[][] matrix) throws Exception {int[][] result = multiplyMatrix(matrix.length, matrix[0].length, matrix, matrix.length, matrix[0].length, 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) throws Exception {printMatrix(matrix);if(checkIdempotentMatrix(matrix)) System.out.println("The matrix is a idempotent matrix");else System.out.println("The matrix is not a idempotent matrix");}public static void main(String[] args) throws Exception {int[][] matrix = {{0, 0},{0,0}};wrapper(matrix);System.out.println("-------------");int[][] matrix1 = {{4, 0},{5, -4}};wrapper(matrix1);}}