Open In App

Python Program to check idempotent matrix

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a N * N matrix and the task is to check matrix is idempotent matrix or not.
Idempotent matrix: A matrix is said to be idempotent matrix if matrix multiplied by itself return the same matrix. The matrix M is said to be idempotent matrix if and only if M * M = M. In idempotent matrix M is a square matrix.
 

idempotent matrix
Examples: 

Input : mat[][] = {{3, -6},  {1, -2}};
Output: Idempotent Matrix

Input : mat[N][N] = {{2, -2, -4}, {-1, 3, 4}, {1, -2, -3}}
Output : Idempotent Matrix.

Python 3




# Python Program to check given matrix
# is idempotent matrix or not.
import math
 
# Function for matrix multiplication.
def multiply(mat, res):
 
    N= len(mat)
    for i in range(0,N):
     
        for j in range(0,N):
         
            res[i][j] = 0
            for k in range(0,N):
                res[i][j] += mat[i][k] * mat[k][j]
 
# Function to check idempotent
# property of matrix.
def checkIdempotent(mat):
 
    N= len(mat)
    # Calculate multiplication of matrix
    # with itself and store it into res.
    res =[[0]*N for i in range(0,N)]
    multiply(mat, res)
 
    for i in range(0,N):
        for j in range(0,N):    
            if (mat[i][j] != res[i][j]):
                return False
    return True
 
# driver Function
mat = [ [2, -2, -4],
        [-1, 3, 4],
        [1, -2, -3] ]
     
# checkIdempotent function call.
if (checkIdempotent(mat)):
    print("Idempotent Matrix")
else:
    print("Not Idempotent Matrix.")
 
# This code is contributed by Gitanjali.


Output

Idempotent Matrix

Time Complexity: O(N3)
Auxiliary Space: O(N2)

Please refer complete article on Program to check idempotent matrix for more details!

Using Numpy:

Install Numpy using command

pip install numpy

This method converts the matrix to a numpy array and uses the @ operator to perform matrix multiplication. The all() function is used to check if all elements in the comparison are True.

Python3




import numpy as np
 
def is_idempotent(matrix):
    # Convert the matrix to a numpy array
    arr = np.array(matrix)
    # Check if the matrix multiplied by itself is equal to the original matrix
    return (arr @ arr == arr).all()
 
matrix = [[3, -6], [1, -2]]
print(is_idempotent(matrix))  # True
 
matrix = [[2, -2, -4], [-1, 3, 4], [1, -2, -3]]
print(is_idempotent(matrix))  # True
 
matrix = [[1, 2], [3, 4]]
print(is_idempotent(matrix))  # False
#This code is contributed by Edula Vinay Kumar Reddy


Output:

True
True
False

Time complexity: O(n^2)
Auxiliary Space: O(n^2)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads