Search code examples
pythonnumpynumpy-ndarrayarray-broadcastingelementwise-operations

Element-wise multiply of multiple numpy 2d arrays


To simplify my question, let's say I have these arrays:

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[2, 2, 2], [3, 3, 3]])
c = np.array([[1, 1, 3], [4, 1, 6]])

I would like to use element-wise multiplication on them so the result will be:

array([[  2,   4,  18],
       [ 48,  15, 108]])

I know I can do a*b*c, but that won't work if I have many 2d arrays or if I don't know the number of arrays. I am also aware of numpy.multiply but that works for only 2 arrays.


Solution

  • Use stack and prod.

    stack will create an array which can be reduced by prod along an axis.

    import numpy as np
    
    a = np.array([[1, 2, 3], [4, 5, 6]])
    b = np.array([[2, 2, 2], [3, 3, 3]])
    c = np.array([[1, 1, 3], [4, 1, 6]])
    
    unknown_length_list_of_arrays = [a, b, c]
    
    d1 = a * b * c
    stacked = np.stack(unknown_length_list_of_arrays)
    d2 = np.prod(stacked, axis=0)
    
    np.testing.assert_equal(d1, d2)