Malintha Malintha - 1 month ago 64
Python Question

How to get element-wise matrix multiplication (Hadamard product) in numpy?

I have two matrices

a = [[1,2][3,4]]
b = [[5,6][7,8]]


I want to get the element-wise prodcut which will be
[[1*5,2*6][3*7,4*8]]
equals to

[[5,12][21,32]]


I tried with numpy

print(np.dot(x,y))


and

print(x*y)


result:
[[19 22][43 50]]


which gives me the matrix multiplication result not element-wise product. How can I get the the element-wise product aka. Hadamard product using built-in functions ?

Answer

Try this,

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)

Result

array([[ 5, 12],
       [21, 32]])