Inverse of a matrix using numpy Inverse of a matrix using numpy numpy numpy

Inverse of a matrix using numpy


The I attribute only exists on matrix objects, not ndarrays. You can use numpy.linalg.inv to invert arrays:

inverse = numpy.linalg.inv(x)

Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're generating matrices, or skip the ones that aren't invertible.

try:    inverse = numpy.linalg.inv(x)except numpy.linalg.LinAlgError:    # Not invertible. Skip this one.    passelse:    # continue with what you were doing

Also, if you want to go through all 3x3 matrices with elements drawn from [0, 10), you want the following:

for comb in itertools.product(range(10), repeat=9):

rather than combinations_with_replacement, or you'll skip matrices like

numpy.array([[0, 1, 0],             [0, 0, 0],             [0, 0, 0]])


Another way to do this is to use the numpy matrix class (rather than a numpy array) and the I attribute. For example:

>>> m = np.matrix([[2,3],[4,5]])>>> m.Imatrix([[-2.5,  1.5],       [ 2. , -1. ]])


Inverse of a matrix using python and numpy:

>>> import numpy as np>>> b = np.array([[2,3],[4,5]])>>> np.linalg.inv(b)array([[-2.5,  1.5],       [ 2. , -1. ]])

Not all matrices can be inverted. For example singular matrices are not Invertable:

>>> import numpy as np>>> b = np.array([[2,3],[4,6]])>>> np.linalg.inv(b)LinAlgError: Singular matrix

Solution to singular matrix problem:

try-catch the Singular Matrix exception and keep going until you find a transform that meets your prior criteria AND is also invertable.