Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
matrix
communitycreator

How to check if a given matrix is an idempotent matrix

abhilash

What is an idempotent matrix?

A matrix is called an idempotent matrix if the matrix when multiplied by itself results in the same matrix, i.e., xx=xx * x = x.

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]]

Algorithm

  1. Multiply the matrix with itself with the help of the algorithm described here.
  2. Compare the result of step 1 with the given matrix.
  3. If the resultant matrix is equal to the given matrix, then the matrix is an idempotent matrix.
  4. Otherwise, the given matrix is not an idempotent matrix.

Code

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);
    }
}

RELATED TAGS

java
matrix
communitycreator
RELATED COURSES

View all Courses

Keep Exploring