Search code examples
pythonarraysnumpymultiplicationlapack

Multiplying a 2d array with each slice of 3d array - Numpy


I am looking for an optimized way of computing a element wise multiplication of a 2d array by each slice of a 3d array (using numpy).

for example:

w = np.array([[1,5], [4,9], [12,15]]) y = np.ones((3,2,3))

I want to get a result as a 3d array with the same shape as y.

Broadcasting using the * operator is not allowed. In my case, the third dimensions is very long and a for loop is not convenient.


Solution

  • Given arrays

    import numpy as np
    
    w = np.array([[1,5], [4,9], [12,15]])
    
    print(w)
    
    [[ 1  5]
     [ 4  9]
     [12 15]]
    

    and

    y = np.ones((3,2,3))
    
    print(y)
    
    [[[ 1.  1.  1.]
      [ 1.  1.  1.]]
    
     [[ 1.  1.  1.]
      [ 1.  1.  1.]]
    
     [[ 1.  1.  1.]
      [ 1.  1.  1.]]]
    

    We can multiple the arrays directly,

    z = ( y.transpose() * w.transpose() ).transpose()
    
    print(z)
    
    [[[  1.   1.   1.]
      [  5.   5.   5.]]
    
     [[  4.   4.   4.]
      [  9.   9.   9.]]
    
     [[ 12.  12.  12.]
      [ 15.  15.  15.]]]
    

    We might note that this produces the same result as np.einsum('ij,ijk->ijk',w,y), perhaps with a little less effort and overhead.