Search code examples
pythonnumpynumpy-ndarrayarray-broadcastingelementwise-operations

How to multiply a vector by an array/matrix element-wise in numpy?


I have a multidimensional array a whose shape is (32,3,5,5) and an array v with a shape of (32,). How could I multiply (i,3,5,5) with (i,) for each i using numpy other than a for-loop?


Solution

  • With a and v as the two arrays, few approaches could be suggested -

    a*v[:,None,None,None]
    a*v.reshape(-1, *[1]*3)
    (a.T * v).T
    np.einsum('i...,i->i...', a, v)