How to Fix numpy.linalg.linalgerror: singular matrix

Numpy.linalg.linalgerror: singular matrix error occurs when you attempt to invert a singular matrix whose determinant is zero that cannot be inverted.

To fix the linalgerror, create a matrix that is not singular, and the determinant is not 0.0.

A singular matrix does not have an inverse, often because its determinant is zero.

Reproducing the error

``````import numpy as np

#create 2x2 matrix
main_matrix = np.array([[21., 21.], [21., 21.]])

# attempt to print the inverse of matrix
print(np.linalg.inv(main_matrix))``````

Output

We got the “LinAlgError: Singular matrix” error because it `main_matrix` is not invertible. It has the same value in all entries, making it a singular matrix with zero determinant.

How to fix it?

``````import numpy as np

# create 2x2 matrix
main_matrix = np.array([[21., 19.], [19., 21.]])

# Printing the inverse of matrix
print(np.linalg.inv(main_matrix))``````

Output

``````[[ 0.2625 -0.2375]
[-0.2375  0.2625]]``````

You can see that the code worked without errors and will print the inverse of the main_matrix.

In this case, the main_matrix is a 2×2 matrix with a non-zero determinant, which is invertible.

The np.linalg.inv() function from the NumPy library is used to find the inverse of the main_matrix.

I hope this solution will fix your error.

Related posts

How to Fix ‘numpy.float64’ object cannot be interpreted as an integer

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