I have an array A
whose shape is (N, N, K)
and I would like to compute another array B
with the same shape where B[:, :, i] = np.linalg.inv(A[:, :, i])
.
As solutions, I see map
and for
loops but I am wondering if numpy
provides a function to do this (I have tried np.apply_over_axes
but it seems that it can only handle 1D array).
with a for
loop:
B = np.zeros(shape=A.shape)
for i in range(A.shape[2]):
B[:, :, i] = np.linalg.inv(A[:, :, i])
with map
:
B = np.asarray(map(np.linalg.inv, np.squeeze(np.dsplit(A, A.shape[2])))).transpose(1, 2, 0)
For an invertible matrix
M
we haveinv(M).T == inv(M.T)
(the transpose of the inverse is equal to the inverse of the transpose).Since
np.linalg.inv
is broadcastable, your problem can be solved by simply transposingA
, callinginv
and transposing the result:For example:
You can check the values of
B
match the inverses of the arrays inA
as expected: