Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse of a matrix using numpy

I'd like to use numpy to calculate the inverse. But I'm getting an error:

'numpy.ndarry' object has no attribute I 

To calculate inverse of a matrix in numpy, say matrix M, it should be simply: print M.I

Here's the code:

x = numpy.empty((3,3), dtype=int) for comb in combinations_with_replacement(range(10), 9):    x.flat[:] = comb    print x.I 

I'm presuming, this error occurs because x is now flat, thus 'I' command is not compatible. Is there a work around for this?

My goal is to print the INVERSE MATRIX of every possible numerical matrix combination.

like image 854
Jake Z Avatar asked Feb 07 '14 22:02

Jake Z


People also ask

How do I find the inverse of a 3x3 matrix?

To find the inverse of a 3x3 matrix, first calculate the determinant of the matrix. If the determinant is 0, the matrix has no inverse. Next, transpose the matrix by rewriting the first row as the first column, the middle row as the middle column, and the third row as the third column.

How do you take the inverse of a NumPy matrix?

We use numpy. linalg. inv() function to calculate the inverse of a matrix. The inverse of a matrix is such that if it is multiplied by the original matrix, it results in identity matrix.


1 Answers

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.     pass else:     # 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]]) 
like image 57
user2357112 supports Monica Avatar answered Sep 21 '22 04:09

user2357112 supports Monica