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.