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

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


For elementwise multiplication of matrix objects, you can use numpy.multiply:

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

Result

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

However, you should really use array instead of matrix. matrix objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use * for elementwise multiplication:

a * b

If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @ does matrix multiplication now:

a @ b  # matrix multiplication


just do this:

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


import numpy as npx = np.array([[1,2,3], [4,5,6]])y = np.array([[-1, 2, 0], [-2, 5, 1]])x*yOut: array([[-1,  4,  0],       [-8, 25,  6]])%timeit x*y1000000 loops, best of 3: 421 ns per loopnp.multiply(x,y)Out: array([[-1,  4,  0],       [-8, 25,  6]])%timeit np.multiply(x, y)1000000 loops, best of 3: 457 ns per loop

Both np.multiply and * would yield element wise multiplication known as the Hadamard Product

%timeit is ipython magic