Batch operation with all matrices stored in n-dimensional numpy array

I have an array with dimensions (4, 4, 6890) which basically contains 6890 4x4 matrices. I need to invert all of them, and I am currently doing it in a loop, which I know is bad practice.

for i in range(0, T.shape[2]):
    T_inv[:,:,i] = np.linalg.inv(T[:,:,i])

      

How can I do this with a single call?

+3


source to share


2 answers


np.linalg.inv

will do it, but you need to rearrange your axes:

 T_inv = np.moveaxis(np.linalg.inv(np.moveaxis(T, -1, 0)), 0, -1)

      



It is best to build T

so that T.shape = (68690, 4, 4)

. It will also help in broadcasting.

+4


source


I'm not sure how to do this using numpy

, but check this out:

[ A 0 0 ]   [ A^(-1)    0        0   ]   [ I 0 0 ]
[ 0 B 0 ] * [   0     B^(-1)     0   ] = [ 0 I 0 ]
[ 0 0 C ]   [   0       0     C^(-1) ]   [ 0 0 I ]

      



A

, B

, C

Are the matrices of the same size (e.g., 4x4) and A^(-1)

, B^(-1)

, C^(-1)

being their inverses. I

is a matrix of ones.

So what does this tell us? We can construct a large sparse block diagonal matrix with all submatrices (4x4) along the diagonal, take the inverse of this large matrix and simply read the inverse submatrices back diagonally across the blocks.

0


source







All Articles