13
votes

What does the error Numpy error: Matrix is singular mean specifically (when using the linalg.solve function)? I have looked on Google but couldn't find anything that made it clear when this error occurs.

2
If you have a singular matrix, then it might indicate that you have some mistake in your matrix filling routine. If your matrix really is singular, then you may get some useful information about it using singular value decomposition. However in this case you need to have a good understanding of linear algebra and numerical computing concepts. - DaveP

2 Answers

24
votes

A singular matrix is one that is not invertible. This means that the system of equations you are trying to solve does not have a unique solution; linalg.solve can't handle this.

You may find that linalg.lstsq provides a usable solution.

1
votes

This function inverts singular matrices as well using numpy.linalg.lstsq:

def inv(m):
    a, b = m.shape
    if a != b:
        raise ValueError("Only square matrices are invertible.")

    i = np.eye(a, a)
    return np.linalg.lstsq(m, i)[0]