Elementwise multiplication of several arrays in Python Numpy

13,616

Solution 1

Your fault is in not reading the documentation:

numpy.multiply(x1, x2[, out])

multiply takes exactly two input arrays. The optional third argument is an output array which can be used to store the result. (If it isn't provided, a new array is created and returned.) When you passed three arrays, the third array was overwritten with the product of the first two.

Solution 2

For anyone stumbling upon this, the best way to apply an element-wise multiplication of n np.ndarray of shape (d, ) is to first np.vstack them and apply np.prod on the first axis:

>>> import numpy as np
>>>
>>> arrays = [
...   np.array([1, 2, 3]),
...   np.array([5, 8, 2]),
...   np.array([9, 2, 0]),
... ]
>>>
>>> print(np.prod(np.vstack(arrays), axis=0))
[45 32  0]

Solution 3

Yes! Simply as doing * to np.arrays

import numpy as np
a=np.array([2,9,4])
b=np.array([3,4,5])
c=np.array([10,5,8])
d=a*b*c
print(d)

Produce:

[ 60 180 160]
Share:
13,616
seb
Author by

seb

Updated on July 27, 2022

Comments

  • seb
    seb almost 2 years

    Coding some Quantum Mechanics routines, I have discovered a curious behavior of Python's NumPy. When I use NumPy's multiply with more than two arrays, I get faulty results. In the code below, i have to write:

    f = np.multiply(rowH,colH)
    A[row][col]=np.sum(np.multiply(f,w))
    

    which produces the correct result. However, my initial formulation was this:

    A[row][col]=np.sum(np.multiply(rowH, colH, w))
    

    which does not produce an error message, but the wrong result. Where is my fault in thinking that I could give three arrays to numpy's multiply routine?

    Here is the full code:

    from numpy.polynomial.hermite import Hermite, hermgauss
    import numpy as np
    import matplotlib.pyplot as plt
    
    dim = 3
    x,w = hermgauss(dim)
    A = np.zeros((dim, dim))
    #build matrix
    for row in range(0, dim):
        rowH = Hermite.basis(row)(x)
        for col in range(0, dim):
            colH = Hermite.basis(col)(x)
            #gaussian quadrature in vectorized form
            f = np.multiply(rowH,colH)
            A[row][col]=np.sum(np.multiply(f,w))
    print(A)
    

    ::NOTE:: this code only runs with NumPy 1.7.0 and higher!

  • seb
    seb about 11 years
    ok, my bad :-). should I remove this post or do you think it's useful for others?
  • mrjrdnthms
    mrjrdnthms about 10 years
    leave it. helped me :)
  • Nagabhushan S N
    Nagabhushan S N over 5 years
    So, is there any option to multiply multiple arrays in a single call (in latest version) or do we have to chain the calls?
  • Shlomi A
    Shlomi A over 2 years
    This answer assume that input arrays are 1D. Taking np.prod(np.array(arrays), axis=0)) works better for multi-dimensional input arrays.