How to check whether matrix is a singular or not in Python

In this article, we will how to check whether a given matrix is a singular matrix or not in Python. A matrix is said to be a singular matrix if its determinant is equal to zero.

Example

Input: [[2, 32, 12],
        [0, 0, 0],
        [23, 6, 9]]
Output: Singular Matrix
Explanation: The determinant of the given matrix is zero.

Input: [[3, 4, 18],
        [9, 18, 1],
        [2, 3, 5]]
Output: Non-Singular Matrix
Explanation: The determinant of the given matrix is not equal to zero.

Mathematical formula for calculating the determinnant

For example given matrix A is [[a, b, c], [d, e, f], [g, h, i]] the determinant of the matrix is

|A| = a(e*i − f*h) − b(d*i − f*g) + c(d*h − e*g)

Method 1:

Approach: 

1. Check the base when the given matrix is 2×2.

2. If the matrix is the determinant value is matrix[0][0]*matrix[1][1] – matrix[1][0]*matrix[0][1].

3. Declare a variable det to store the determinant.

4. Apply the formulae and store the result in det.

5. Finally, return the determinant.

def get_cofactor(matrix, i, j):
    return [row[: j] + row[j+1:] for row in (matrix[: i] + matrix[i+1:])]
def is_singular(matrix):
    n = len(matrix)
    if (n == 2):
        val = matrix[0][0]*matrix[1][1] - matrix[1][0]*matrix[0][1]
        return val
    
    det = 0
    for i in range(n):
        s = (-1)**i
        sub_det = is_singular(get_cofactor(matrix, 0, i))
        det += (s*matrix[0][i]*sub_det)
    return det
matrix = [[78, 45, 4], [0, 0, 0], [7, 4, -54]]
n = len(matrix)
print("The given matrix")
for i in range(n):
    for j in range(n):
        print(matrix[i][j], end=' ')
    print()
if(is_singular(matrix)):
    print("The given matrix is non-Singular")
else:
    print("The given matrix is singular")

Output

The given matrix
78 45 4
0 0 0 
7 4 -54
The given matrix is singular

Method 2: Using NumPy

NumPy module in Python has an inbuilt linalg.det() function to calculate the determinant of a matrix.

1. Use linalg.det() function to calculate the determinant.

2. Check whether the determinant is equal to zero. If yes print “Singular Matrix”.

3. Else, print “Non-Singular matrix”.

import numpy as np
arr = np.array([[1,- 2, 2],
                [9, 9, 8],
                [7, 8, 0]])
if (np.linalg.det(arr)):
    print("Non Singular matrix")
else:
    print("Singular Matrix")

Output

Non Singular matrix

Also read:

Leave a Reply

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