Search code examples
pythonnumpyscientific-computing

product of arrays of different sizes in numpy


I have two arrays, x = np.arange(3) = [0,1,2,3] and y = np.arange(4) = [0,1,2].

Is there a numpy function that gives a table of all of their products ? Or example for times this would be:

x*y = [[0,0,0,0], [0,1,2,3], [0,2,4,6]]

This is not the inner product or the scalar product. This could be called the "tensor product" or something.


Solution

  • For the outer product specifically there is np.outer:

    >>> x = np.arange(3)
    >>> y = np.arange(4)
    >>> np.outer(x, y)
    array([[0, 0, 0, 0],
           [0, 1, 2, 3],
           [0, 2, 4, 6]])
    >>> 
    

    More generally you can achieve this with broadcasting:

    >>> x = np.arange(3)
    >>> y = np.arange(4)
    >>> x[..., None] * y[None, ...]
    array([[0, 0, 0, 0],
           [0, 1, 2, 3],
           [0, 2, 4, 6]])
    >>> 
    

    To apply a function with two parameters over all pairs, you would define it as:

    def f(x, y):
        return x * y
    

    You can then use it as follows:

    >>> f(x[..., None], y[None, ...])
    array([[0, 0, 0, 0],
           [0, 1, 2, 3],
           [0, 2, 4, 6]])
    >>> 
    

    To apply a function with one parameter over the outer product you would do:

    np.exp(np.outer(x, y))
    

    or

    np.exp(x[..., None] * y[None, ...])
    

    More on broadcasting: