Search code examples
pythonarraysnumpyarray-broadcasting

Is there a function for automatic broadcasting when multiplying two numpy arrays with different shapes?


I want to multiply two numpy arrays with different shapes. The result should be broadcasted in such a way that e.g. the multiplication of arrays with shape (3,) and (5,) returns an array with shape (3,5). I know that this is possible using array1[:,numpy.newaxis]*array2[numpy.newaxis,:]. But what I am looking for is something more general, a function that does also automatically multiply the arrays with shapes (3,5) and (4,) to an array with shape (3,5,4). Is there any numpy function to do this? Sure, a can write myself a function but is there any function existing?

So I am looking for a function numpy.func(array1, array2) that does return an array array3 with shape (*array1.shape, *array2.shape) and values array3[i1,j1,..,i2,j2,..] = array1[i1,j1,...]*array2[i2,j2,...].

Thanks


Solution

  • Take a look at numpy.multiply.outer. outer is a standard method that all the "ufuncs" have.

    For example,

    In [19]: a   # a has shape (3, 4)
    Out[19]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    
    In [20]: b   # b has shape (5,)
    Out[20]: array([0, 1, 2, 3, 4])
    
    In [21]: c = np.multiply.outer(a, b)
    
    In [22]: c.shape
    Out[22]: (3, 4, 5)
    
    In [23]: c[1, 2, 3]
    Out[23]: 18
    
    In [24]: a[1, 2]*b[3]
    Out[24]: 18