Search code examples
pythonnumpymultidimensional-arraynumpy-ndarraymultiplication

How can I multiply more than 3 vectors at once in NumPy


I'm looking for a vectorised way to multiply more than 3 vectors in NumPy.

As an example,

X = np.array([1,2,3])
Y = np.array([4,5,6])
Z = np.array([7,8,9])


Multiply([X,Y,Z])

would produce as an output

np.array([28, 80, 162])

The vectors I want to multiply need not to be defined separately as I did above. The could be, for example, the rows (or columns) of a matrix, and in that case I would like to multiply all the rows (or columns) of such a matrix.

Helps appreciated :)


Solution

  • You can use the reduce method of the ufunc:

    >>> np.multiply.reduce((X, Y, Z))                                                                                                                                                                                                                        
    array([ 28,  80, 162])
    

    What's going on here is that the ufunc np.multiply, which looks and acts like function, is technically an instance of the class numpy.ufunc; all ufuncs have four special methods, one of them being .reduce(), which does what you're looking for in this case and produces a 1d result from multiple same-length 1d arrays.

    The default axis is 0; if you want to work along the other axis, just specify that:

    >>> np.multiply.reduce((X, Y, Z), axis=1)                                                                                                                                                                                                                
    array([  6, 120, 504])