Given a matrix and the task is to check matrix is an involutory matrix or not.
Involutory Matrix: A matrix is said to be an involutory matrix if the matrix multiplies by itself and returns the identity matrix. The involutory matrix is the matrix that is its own inverse. The matrix A is said to be an involutory matrix if A * A = I. Where I is the identity matrix.
Examples:
Input : mat[N][N] = {{1, 0, 0}, {0, -1, 0}, {0, 0, -1}} Output : Involutory Matrix Input : mat[N][N] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}} Output : Involutory Matrix
Python3
# Program to implement involutory matrix. N = 3 ; # Function for matrix multiplication. def multiply(mat, res): for i in range (N): for j in range (N): res[i][j] = 0 ; for k in range (N): res[i][j] + = mat[i][k] * mat[k][j]; return res; # Function to check involutory matrix. def InvolutoryMatrix(mat): res = [[ 0 for i in range (N)] for j in range (N)]; # multiply function call. res = multiply(mat, res); for i in range (N): for j in range (N): if (i = = j and res[i][j] ! = 1 ): return False ; if (i ! = j and res[i][j] ! = 0 ): return False ; return True ; # Driver Code mat = [[ 1 , 0 , 0 ], [ 0 , - 1 , 0 ], [ 0 , 0 , - 1 ]]; # Function call. If function # return true then if part # will execute otherwise # else part will execute. if (InvolutoryMatrix(mat)): print ( "Involutory Matrix" ); else : print ( "Not Involutory Matrix" ); # This code is contributed by mits |
Involutory Matrix
Time Complexity: O(N3)
Auxiliary Space: O(N2)
Please refer complete article on Program to check Involutory Matrix for more details!
Using Numpy:
Note: Before running the code please install the Numpy library using the command below
pip install numpy
Another approach is to use the numpy library to check if the matrix is involutory. This can be done by using the numpy.allclose function to compare the matrix with its inverse.
For example, the following code snippet checks if a matrix is involutory:
Python3
import numpy as np def is_involutory(matrix): # Calculate the inverse of the matrix using the numpy linalg module inverse = np.linalg.inv(matrix) # Check if the matrix is equal to its inverse using numpy.allclose return np.allclose(matrix, inverse) # Example usage matrix = np.array([[ 1 , 0 , 0 ], [ 0 , - 1 , 0 ], [ 0 , 0 , - 1 ]]) print (is_involutory(matrix)) # prints True #This code is contributed by Edula Vinay Kumar Reddy |
Output: True
This approach has the advantage of being more concise and easier to read, and it also takes advantage of the optimized linear algebra routines provided by numpy. Space complexity is O(N^2) and the time complexity of this approach will depend on the complexity of the matrix inverse calculation, which is generally O(N^3) for dense matrices.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!