pythonnumpymatrixmatrix-multiplicationelementwise-operations

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


I have two matrices

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

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

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

I have tried np.dot(a,b) and a*b but both give the result matrix([[19, 22], [43, 50]])

which is the matrix product, not the element-wise product. How can I get the the element-wise product (aka Hadamard product) using built-in functions?


Solution

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

    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]])
    

    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