Check if 2D NumPy Array or Matrix is Symmetric

In this article we will learn how to check if 2D NumPy array or matrix is symmetric.

Given a NumPy array we need to check if it is symmetric. It means, if the given array and its transpose are equal then we can say that the given array is symmetric. The transpose of a matrix is calculated by interchanging its rows into columns or columns into rows.

For example: A sample matrix or 2D NumPy array is as follows,

a = [[ 1, 3, 5 ]
     [ 3, 2, 4 ]
     [ 5, 4, 1 ]] 

Transpose of this Matrix is,

b = [[ 1, 3, 5 ]
     [ 3, 2, 4 ]
     [ 5, 4, 1 ]] 

Both the 2D Array and its transpose are equal, so we can say that the given Matrix is a symmetric matrix.

There are multiple ways to check if 2D NumPy Array or matrix is symmetric or not. Lets discuss all the methods one by one with proper approach and a working code example.

1.) Using == operator, all() and transpose() methods

Numpy array has a method transpose(). The transpose() method is used to get the transpose of an array. Then the given array and the transpose are checked for equality.

The two numpy arrays when compared using the == operator returns a array of Boolean values with length same as the comparing arrays. The Boolean array represents at which positions elements in both arrays are equal. The True value, represents that element in both arrays are equal at that specific position and False value represent that corresponding element in both arrays are not equal.

The all() method is used to check if all the elements present in the array are equal to True. The all() method takes array as input parameter and returns a Boolean value.

Syntax of all()

numpy.all(array, axis = None)

Parameters:
    array          = The array to be passed to the function.
    axis           = The default, axis=None

Returns:
    Returns an Boolean value.

Syntax of transpose()

numpy.transpose(a, axes=None)

Parameters:
    array          = The array to be passed to the function.
    axis           = The default, axis=None

Returns:
    Returns the transpose of array.

Approach

  • Import numpy library and create numpy array
  • Using the transpose() method get the transpose of the given array
  • Check if both arrays are of equal shape using shape() method
  • Compare the arrays using == operator and it returns a Boolean array
  • Apply all() method on Boolean array, if it returns true then print The array is Symmetric else print the array is not Symmetric.

Source code

import numpy as np

# creating numpy array
a = np.array([[ 1, 3, 5 ],
              [ 3, 2, 4 ],
              [ 5, 4, 1 ]])

# Transpose of given Array
b = a.transpose()

# checking if both the arrays are of equal size
if a.shape == b.shape:
    # comparing the arrays using == and all() method
    if (a == b).all():
        print("The Array or Matrix is Symmetric")
    else:
        print("The Array / Matrix is Not Symmetric")
else:
    print("The Array / Matrix is Not Symmetric")

OUTPUT:

The Array or Matrix is Symmetric

2.) Using array_equal() method and transpose()

The transpose() method is used to get the transpose of an array. Then the given array and the transpose are checked
for equality. The array_equal() method is a built-in numpy method, it takes two arrays as arguments and returns a Boolean
value, True represent that the arrays are equal and false represent that the arrays are not equal.

Syntax of array_equal()

numpy.array_equal(array_1, array_2)

Syntax of transpose()

numpy.transpose(a, axes=None)

Parameters:
    array          = The array to be passed to the function.
    axis           = The default, axis=None

Returns:
    Returns the transpose of array.

Approach

  1. import numpy library and create numpy array
  2. Using the transpose() method get the transpose of the given array
  3. Check if both arrays are of equal shape using shape() method
  4. If shape of two arrays is not equal then print arrays not equal else move to next step
  5. Pass the two arrays to array_equal() method, if it returns true then print that the array is Symmetric else print that the array is not Symmetric.

Source code

import numpy as np

# creating numpy array
a = np.array([[ 1, 3, 5 ],
              [ 3, 2, 4 ],
              [ 5, 4, 1 ]])

# Transpose of given Array
b = a.transpose()

# Comparing both arrays using array_equal() method
if np.array_equal(a, b):
    print("The array is Symmetric")
else:
    print("The array is Not Symmetric")

OUTPUT:

The array is Symmetric

3.) Using transpose() and Flattening the arrays and comparing elements one-by-one

The transpose() method is used to get the transpose of an array. Then the given array and the transpose are checked
for equality. The flatten() method is a built-in numpy method, it takes an array as arguments and returns a flattened array i.e.
1d array. Both the array and the transpose of the array are flattened. Now these flatten arrays can be iterated and compared with ease.

Syntax of flatten()

ndarray.flatten()

Approach

  1. import numpy library and create numpy array
  2. Using the transpose() method get the transpose of the given array
  3. Check if both arrays are of equal shape using shape() method
  4. if shape of two arrays is not equal then print arrays not equal else move to next step
  5. Initialize as boolean flag and set it to False.
  6. Flatten both the arrays using flatten() method
  7. Iteratively compare the each element of the both arrays using for loop
  8. if any of the element is not equal then set the not_equal flag to True and break the loop
  9. Outside the loop check the not_equal flag and if it is true print The array is Symmetric else print The array is not Symmetric.

Source code

import numpy as np

# creating numpy array
a = np.array([[ 1, 3, 5 ],
              [ 3, 2, 4 ],
              [ 5, 4, 1 ]])

# Transpose of given Array
b = a.transpose()

#initialise boolean flag
not_equal = False

if a.shape == b.shape:
    # flattening both the arrays using flatten() method
    a = a.flatten()
    b = b.flatten()
    # iterating elements from both arrays at once using zip()
    for i, j in zip(a, b):
        if i != j:
            # if any element is not equal set not_equal flag to true and break
            not_equal = True
            break
    if not not_equal:
        print("The array is Symmetric")
    else:
        print("The array is NOT Symmetric")
else:
    print("The array is NOT Symmetric")

OUTPUT:

The array is Symmetric

4.) Using transpose() and ravel() method

This Approach is almost similar to the previous one, but the only difference is we use ravel() method to flatten the array and rest remains same. The ravel() method is a built-in numpy method, it takes an array as arguments and returns a flattened array i.e. 1d
array. Now these flattened arrays can be iterated and compared with ease.

Syntax of ravel()

ndarray.ravel()

Approach

  1. import numpy library and create numpy array
  2. Using the transpose() method get the transpose of the given array
  3. Check if both arrays are of equal shape using shape() method
  4. if shape of two arrays is not equal then print arrays not equal else move to next step
  5. Initialize as boolean flag and set it to False.
  6. Flatten both the arrays using ravel() method
  7. Iteratively compare the each element of the both arrays using for loop
  8. if any of the element is not equal then set the not_equal flag to True and break the loop
  9. Outside the loop check the not_equal flag and if it is true print The array is Symmetric else print The array is not Symmetric.

Source code

import numpy as np

# creating numpy array
a = np.array([[ 1, 3, 5 ],
              [ 3, 2, 4 ],
              [ 5, 4, 1 ]])

# Transpose of given Array
b = a.transpose()

#initialise boolean flag
not_equal = False

# checking if both the arrays are of equal size
if a.shape == b.shape:
    # flattening both the arrays using ravel() method
    a = a.ravel()
    b = b.ravel()
    # iterating elements from both arrays at once using zip()
    for i, j in zip(a, b):
        if i != j:
            # if any element is not equal set not_equal flag to true and break
            not_equal = True
            break
    if not not_equal:
        print("The array is Symmetric")
    else:
        print("The array is NOT Symmetric")
else:
    print("The array is NOT Symmetric")

OUTPUT:

The array is Symmetric

5.) Using array_equiv() to check if the Matrix is Symmetrical

Use the transpose() method to get the transpose of the given method, then check if the both arrays are equal. The array_equiv() method is a built-in numpy method, it takes two arrays as arguments and returns a boolean value, True represent that the arrays are equal and False represent that the arrays are not equal.

Syntax of array_equiv()

numpy.array_equiv(array_1, array_2)

Approach

  1. import numpy library and create numpy array
  2. Using the transpose() method get the transpose of the given array
  3. Check if both arrays are of equal shape using shape() method
  4. if shape of two arrays is not equal then print arrays not equal else move to next step
  5. pass the two arrays to array_equiv() method, if it returns true print The array is Symmetric else print The array is not Symmetric.

Source code

import numpy as np

# creating numpy array
a = np.array([[ 1, 3, 5 ],
              [ 3, 2, 4 ],
              [ 5, 4, 1 ]])

# Transpose of given Array
b = a.transpose()

if np.array_equiv(a, b):
    print("The array is Symmetric")
else:
    print("The array is NOT Symmetric")

OUTPUT:

The array is Symmetric

6.) Using allclose() method

Use the transpose() method to get the transpose of the given method, then check if the both arrays are equal. The allclose() method is a built-in numpy method, it takes two arrays as arguments and atol (absolute tolerance), rtol (relative tolerance) as optional arguments which are used to specify the tolerance i.e the value by which values can differ. It returns a boolean value, True represent that the elements in the arrays are very very close to each other (i.e equal) and False represent that the arrays are not equal.

NOTE:

In the case of checking equality of two arrays we set the atol=0 and rtol=0. So that the allclose() will return true only when all the elements of both arrays are exactly equal.

Syntax of allclose()

np.allclose(a, b,rtol=0, atol=0)

Approach

  1. import numpy library and create numpy array
  2. Using the transpose() method get the transpose of the given array
  3. Check if both arrays are of equal shape using shape() method
  4. if shape of two arrays is not equal then print arrays not equal else move to next step
  5. pass the two arrays to allclose() method, if it returns true print The array is Symmetric else print The array is not Symmetric.

Source code

import numpy as np

# creating numpy array
a = np.array([[ 1, 3, 5 ],
              [ 3, 2, 4 ],
              [ 5, 4, 1 ]])

# Transpose of given Array
b = a.transpose()

if np.allclose(a, b,rtol=0, atol=0):
    print("The array is Symmetric")
else:
    print("The array is NOT Symmetric")

OUTPUT:

The array is Symmetric

Summary

We learned how to check if two NumPy Arrays are symmetrical or not.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top