How to Check if a Matrix is Symmetric in Python

How to Check if a Matrix is Symmetric in Python

A symmetric matrix is a square matrix that is equal to its transpose. This means that the matrix remains unchanged when its rows are swapped with its columns.

Consider the matrix illustrated in the diagram, where a diagonal line running from the top left to the bottom right acts like a mirror.

Each entry on one side of this line is a reflection of the corresponding entry on the other side. For example, the elements ‘b’ and ‘b’ mirror each other across the diagonal, as do ‘c’ and ‘c’, demonstrating the symmetry of this matrix around its diagonal. 

Checking Matrix Symmetry in Python

Before checking if a matrix is symmetric, it is essential to confirm that the matrix is square. A square matrix has an equal number of rows and columns, a necessary condition for symmetry since the concept of “mirroring” across the diagonal only makes sense when the matrix has the same dimensions in both directions. To learn more about square matrices, refer to our post on: How to Create Square and Rectangle Matrices in Python.

To validate the symmetry of matrices computationally, we’ll employ Python’s NumPy library, specifically using the .T attribute for transposing the matrix and the np.array_equal() function to compare the original and transposed matrices for equality. Below are examples of both a symmetric and a non-symmetric matrix, and how to check for symmetry.

1. Symmetric Matrix Example:

import numpy as np

# Define a symmetric matrix
sym_matrix = np.array([[1, 2, 3],
                       [2, 5, 6],
                       [3, 6, 7]])

# Check if the matrix is symmetric using the .T attribute
print("Symmetric matrix check (sym_matrix):", 
       np.array_equal(sym_matrix, sym_matrix.T))

Output:

Symmetric matrix check (sym_matrix): True

2. Non-Symmetric Matrix Example:

import numpy as np

# Define a non-symmetric matrix
non_sym_matrix = np.array([[1, 2, 3],
                           [0, 5, 6],
                           [7, 8, 9]])

# Check if the matrix is symmetric using the .T attribute
print("Symmetric matrix check (non_sym_matrix):", 
       np.array_equal(non_sym_matrix, non_sym_matrix.T))

Output:

Symmetric matrix check (non_sym_matrix): False

These examples clearly demonstrate how to check the symmetry of a matrix in Python. The .T attribute provides a convenient and quick way to transpose a matrix and verify if it is symmetric by comparing it to its original form.

Leave a Reply

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