Python Program to check idempotent matrix
Last Updated :
10 Jan, 2023
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.
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
import math
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]
def checkIdempotent(mat):
N = len (mat)
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
mat = [ [ 2 , - 2 , - 4 ],
[ - 1 , 3 , 4 ],
[ 1 , - 2 , - 3 ] ]
if (checkIdempotent(mat)):
print ( "Idempotent Matrix" )
else :
print ( "Not 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):
arr = np.array(matrix)
return (arr @ arr = = arr). all ()
matrix = [[ 3 , - 6 ], [ 1 , - 2 ]]
print (is_idempotent(matrix))
matrix = [[ 2 , - 2 , - 4 ], [ - 1 , 3 , 4 ], [ 1 , - 2 , - 3 ]]
print (is_idempotent(matrix))
matrix = [[ 1 , 2 ], [ 3 , 4 ]]
print (is_idempotent(matrix))
|
Output:
True
True
False
Time complexity: O(n^2)
Auxiliary Space: O(n^2)
Share your thoughts in the comments
Please Login to comment...