0

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?

3
  • What is inefficient of A = [np.power(A[i, :, :, :], b) for b in B)] ? The a**b is necessary even if b is big. Commented Mar 14, 2019 at 22:59
  • 1
    np.power(A, B[:,None,None,None]) - that is, expand the dimensions of B so it broadcasts with A. Commented Mar 14, 2019 at 23:07
  • Or (A.T**B).T. Commented Mar 14, 2019 at 23:36

1 Answer 1

1

This will work:

C = A ** B[:,None,None,None]
print (C)

Output:

[[[[  1   1]
   [  1   1]]

  [[  1   1]
   [  1   1]]]


 [[[  8   9]
   [ 10  11]]

  [[ 12  13]
   [ 14  15]]]


 [[[256 289]
   [324 361]]

  [[400 441]
   [484 529]]]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.