No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

A symmetric matrix is one where the transpose of the matrix is equal to the original matrix. Here’s a simple Python program to check if a given matrix is symmetric:

  • Home
  • Python
  • A symmetric matrix is one where the transpose of the matrix is equal to the original matrix. Here’s a simple Python program to check if a given matrix is symmetric:
def is_symmetric(matrix):
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] != matrix[j][i]:
                return False
    return True

# Example usage
matrix = [
    [1, 2, 3],
    [2, 1, 4],
    [3, 4, 1]
]

if is_symmetric(matrix):
    print("The matrix is symmetric.")
else:
    print("The matrix is not symmetric.")

Alternatively, if you’re using NumPy, you can check for symmetry more efficiently

import numpy as np

def is_symmetric(matrix):
    return np.array_equal(matrix, matrix.T)

# Example usage
matrix = np.array([
    [1, 2, 3],
    [2, 1, 4],
    [3, 4, 1]
])

if is_symmetric(matrix):
    print("The matrix is symmetric.")
else:
    print("The matrix is not symmetric.")

Here’s a more advanced method using NumPy’s allclose() function, which allows for a tolerance level when checking symmetry—useful for floating-point matrices:

import numpy as np

def is_symmetric(matrix, tol=1e-8):
    return np.allclose(matrix, matrix.T, atol=tol)

# Example usage
matrix = np.array([
    [1.00000001, 2, 3],
    [2, 1, 4],
    [3, 4, 1]
])

if is_symmetric(matrix):
    print("The matrix is symmetric.")
else:
    print("The matrix is not symmetric.")

This method is particularly useful when dealing with floating-point precision errors, ensuring that minor differences don’t incorrectly classify a matrix as asymmetric.

Leave A Comment

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