Let's say we have a 4D-array A of shape (n, m, g, h) and a 1D-array B of shape (n).
So I want to do a power operation for every 3D sub-array of A (m, g, h) with every element of B (which is an int).
A = np.arange(24).reshape(3, 2, 2, 2)
>>>array([[[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]]],
[[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]],
[[[16, 17],
[18, 19]],
[[20, 21],
[22, 23]]]]
B = np.arange(3)
>>>array([0, 1, 2])
The result that I want is:
C = somefunc(A, B) # just an example, can be anything
>>>array([[[[ (ignore, 0^0), 1],
[ 1, 1]],
[[ 1, 1],
[ 1, 1]]],
[[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]],
[[[256, 289],
[324, 361]],
[[400, 441],
[484, 529]]]]
What is the best way to get the desired result?
I thought about something like:
A = [np.power(A[i, :, :, :], B[i]) for i in range(B.size)]
But that would be quite inefficient if B.size is a big number. Any other ideas?
A = [np.power(A[i, :, :, :], b) for b in B)]? Thea**bis necessary even ifbis big.np.power(A, B[:,None,None,None])- that is, expand the dimensions ofBso it broadcasts withA.(A.T**B).T.