How to check if a matrix is symmetric in NumPy?

Given a NumPy matrix, we have to whether it is a symmetric matrix or not. By Pranit Sharma Last updated : December 23, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a matrix and we need to create a function with the arguments (arr, tol=1e-8) that returns a boolean value that tells the user whether the matrix is symmetric (the symmetric matrix is equal to its transpose).

Checking if a matrix is symmetric

To check whether a given matrix is a symmetric matrix or not in NumPy, you need to check whether the original matrix is equal to its transpose. If the matrix is equal to its transpose, then it will be a symmetric matrix.

Steps/Algorithm

Below are the steps to check the symmetric matrix:

  • Create a function by passing the matrix and size.
  • Find the transpose of the matrix using the numpy.transpose() matrix.
  • Now, check whether the given matrix is equal to the transpose matrix using the numpy.array.equal() method.
  • If the matrix and its transpose are equal, then returns True (i.e., it will be a symmetric matrix); False, otherwise.

Let us understand with the help of an example,

Python code to check if a matrix is symmetric in NumPy

# Import numpy
import numpy as np

# Defining a function to check symmetric matrix
def isSymmetric(mat, N):
    transmat = np.array(mat).transpose()
    if np.array_equal(mat, transmat):
        return True
    return False

# Creating a numpy array
arr = np.array([[2, 3, 6], [3, 4, 5], [6, 5, 9]])

# Display original array
print("Original Array:\n", arr, "\n")

# Checking whether matrix is symmetric or not
res = isSymmetric(arr, 3)

# Display result
print("Is matrix symmetric:\n", res)

Output

Example: How to check if a matrix is symmetric in NumPy?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.