Python program to check whether a given matrix is an idempotent or not

In this article, we will check whether a given matrix is an idempotent matrix or not in Python.

Example

Input: matrix[][] = {{3, -6},
                     {1, -2}}
Output: Idempotent matrix

Input: matrix[][] = {{1, 2},
                     {3, 4}}
Output: Not a Idempotent matrix

What is an Idempotent matrix?

A matrix is said to be an idempotent matrix, when the given matrix is multiplied by itself returns the same matrix as result. The matrix A is said to idempotent if and only if A*A = A. For example

[[1, 0, 0],       [[1, 0, 0],          [[1, 0, 0],
 [0, 1, 0],   *    [0, 1, 0],     =     [0, 1, 0],
 [0, 0, 1]]        [0, 0, 1]]           [0, 0, 1]]

Check whether a given matrix is an Idempotent matrix in Python

1. Create an empty matrix result of the size of the given matrix which the result of the matrix multiplication, and initialize its value to zero.

2. Create a function matrix_multiply that return the matrix*matrix value

  • Iterate the matrix from range 0 to n as three nested loops
  • Now calculate the matrix multiplication and store its value in result i.e.
    result[i][j] += matrix[i][k]*matrix[k][j]

3. Now compare the given matrix matrix with the result, if not equal return False.

4. Else, return True

def matrix_multiply(matrix, result):
    n = len(matrix)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                result[i][j] += matrix[i][k]*matrix[k][j]
def Idempotent(matrix):
    n = len(matrix)
    result = [[0]*n for i in range(n)]
    matrix_multiply(matrix, result)
    for i in range(n):
        for j in range(n):
            if(matrix[i][j] != result[i][j]):
                return False
    return True
matrix = [[2, -2, -4],
          [-1, 3, 4],
          [1, -2, -3]]
if (Idempotent(matrix)):
    print("Idempotent matrix")
else:
    print("Not an Idempotent matrix")

Output

Idempotent matrix

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *