Skip to content
Related Articles

Related Articles

Python Program to check if a matrix is symmetric

View Discussion
Improve Article
Save Article
  • Last Updated : 11 Jan, 2022
View Discussion
Improve Article
Save Article

A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row.

Examples: 

Input : 1 2 3
        2 1 4
        3 4 3
Output : Yes

Input : 3 5 8
        3 4 7
        8 5 3
Output : No

A Simple solution is to do following. 

1) Create transpose of given matrix. 
2) Check if transpose and given matrices are same or not.  

Python




# Simple Python code for check a matrix is
# symmetric or not.
   
# Fills transpose of mat[N][N] in tr[N][N]
def transpose(mat, tr, N):
    for i in range(N):
        for j in range(N):
            tr[i][j] = mat[j][i]
   
# Returns true if mat[N][N] is symmetric, else false
def isSymmetric(mat, N):
      
    tr = [ [0 for j in range(len(mat[0])) ] for i in range(len(mat)) ]
    transpose(mat, tr, N)
    for i in range(N):
        for j in range(N):
            if (mat[i][j] != tr[i][j]):
                return False
    return True
   
# Driver code
mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]
if (isSymmetric(mat, 3)):
    print "Yes"
else:
    print "No"
  
# This code is contributed by Sachin Bisht

Output : 

 Yes

Time Complexity : O(N x N) 
Auxiliary Space : O(N x N)

An Efficient solution to check a matrix is symmetric or not is to compare matrix elements without creating a transpose. We basically need to compare mat[i][j] with mat[j][i].  

Python




# Efficient Python code for check a matrix is
# symmetric or not.
  
# Returns true if mat[N][N] is symmetric, else false
def isSymmetric(mat, N):
    for i in range(N):
        for j in range(N):
            if (mat[i][j] != mat[j][i]):
                return False
    return True
   
# Driver code
mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]
if (isSymmetric(mat, 3)):
    print "Yes"
else:
    print "No"
  
# This code is contributed by Sachin Bisht

Output: 

Yes

Time Complexity : O(N x N) 
Auxiliary Space : O(1)

Please refer complete article on Program to check if a matrix is symmetric for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!