user15581766
user15581766

Reputation:

Difference between NumPy.dot() and ‘*’ operation in Python

On this page I found that: v1 * v2 == np.multiply (v1, v2)

But on another page I found: v1 * v2 == v1.dot (v2)

Please, could you explain to me right ?

Upvotes: 1

Views: 61

Answers (1)

ForceBru
ForceBru

Reputation: 44848

a * b is np.multiply(a, b). np.dot is the dot product, which is the same as np.multiply only if one of the operands is a scalar (a number, as opposed to a vector or a matrix).

Example with matrices

>>> a = np.arange(0, 9).reshape(3, 3)
>>> b = np.arange(10, 19).reshape(3, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b
array([[10, 11, 12],
       [13, 14, 15],
       [16, 17, 18]])
>>> a * b # elementwise multiplication
array([[  0,  11,  24],
       [ 39,  56,  75],
       [ 96, 119, 144]])
>>> np.multiply(a, b) # elementwise multiplication
array([[  0,  11,  24],
       [ 39,  56,  75],
       [ 96, 119, 144]])
>>> a @ b # matrix multiplication
array([[ 45,  48,  51],
       [162, 174, 186],
       [279, 300, 321]])
>>> np.dot(a, b) # matrix multiplication
array([[ 45,  48,  51],
       [162, 174, 186],
       [279, 300, 321]])

Upvotes: 1

Related Questions