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

后端 未结 4 1452
無奈伤痛
無奈伤痛 2020-11-27 15:05

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*

4条回答
  •  忘掉有多难
    2020-11-27 15:12

    Try this:

    a = np.matrix([[1,2], [3,4]])
    b = np.matrix([[5,6], [7,8]])
    
    #This would result a 'numpy.ndarray'
    result = np.array(a) * np.array(b)
    

    Here, np.array(a) returns a 2D array of type ndarray and multiplication of two ndarray would result element wise multiplication. So the result would be:

    result = [[5, 12], [21, 32]]
    

    If you wanna get a matrix, the do it with this:

    result = np.mat(result)
    

提交回复
热议问题