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?
source to share
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.
source to share