awareeye
awareeye

Reputation: 3061

Sympy - find inverse of matrix only at a particular location?

I have an 8 by 8 matrix in Sympy. Inverting the entire matrix takes too long since the symbolic expression for each cell in the matrix is fairly complicated in my case. Also, I am only interested in the value of the inverse of a matrix for a single cell (first row and first column). Is there any way to compute the inverse only at a single location instead of computing the value at all 64 locations of the matrix?

Thanks!

Upvotes: 1

Views: 427

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14500

The general formula for the inverse is calculated from the transposed matrix of cofactors and the determinant so

In [8]: M = Matrix([[1, 4, 7], [3, 0, 5], [-1, 9, 11]])                                                                           

In [9]: M                                                                                                                         
Out[9]: 
⎡1   4  7 ⎤
⎢         ⎥
⎢3   0  5 ⎥
⎢         ⎥
⎣-1  9  11⎦

In [10]: M.inv()                                                                                                                  
Out[10]: 
⎡45/8   -19/8  -5/2⎤
⎢                  ⎥
⎢19/4   -9/4    -2 ⎥
⎢                  ⎥
⎣-27/8  13/8   3/2 ⎦

In [11]: M.cofactor(0, 0) / M.det()                                                                                               
Out[11]: 45/8

This requires computing two determinants: one for the whole matrix and one for the cofactor. In big-O terms this is O(n**3) (same as the inverse) but it might be faster than computing the inverse.

If the problem is expression blow up then I think that using cofactor and determinant will not help since the determinant calculations will still be slow. In that case you need to give an example expression that demonstrates the problem.

Upvotes: 2

Related Questions