Element-Wise Multiplication in NumPy Element-wise multiplication, also known as the Hadamard Product is the multiplication of every element in a matrix by its corresponding element on a secondary matrix.

To perform element-wise matrix multiplication in NumPy, use either the np.multiply() function or the * (asterisk) character. These operations must be performed on matrices of the same dimension.

Python Matrix Element-Wise Multiplication with np.multiply()

To multiply matrices, pass them as arguments to np.multply() and it will return a new matric containing the result.

import numpy as np

m1 = np.array([[2,6,3,9,20],[43,35,28,3,7]])
m2 = np.array([[5,16,4,14,22],[18,8,19,3,3]])

print(np.multiply(m1,m2))
[[ 10  96  12 126 440]
[774 280 532   9  21]]

Element-Wise Multiplication On Specific Rows and Columns

To perform the multiplication on specific rows or columns specify them when passing the matrices into np.multiply() like this:

import numpy as np

m1 = np.array([[2,6,3,9,20],[43,35,28,3,7]])
m2 = np.array([[5,16,4,14,22],[18,8,19,3,3]])

print(np.multiply(m1[0,:],m2[0,:]))
[ 10  96  12 126 440]

Here is another example specifying columns to multiply:

import numpy as np

m1 = np.array([[2,6,3,9,20],[43,35,28,3,7]])
m2 = np.array([[5,16,4,14,22],[18,8,19,3,3]])

print(np.multiply(m1[:,2],m2[:,0]))
[ 15 504]

Multiply Matrices in Python with the * Operator

The native Python * (asterisk) operator will perform element-wise multiplication of matrices and return a new matrix containing the result.

import numpy as np

m1 = np.array([[2,6,3,9,20],[43,35,28,3,7]])
m2 = np.array([[5,16,4,14,22],[18,8,19,3,3]])

print(m1 * m2)
[[ 10  96  12 126 440]
[774 280 532   9  21]]

Related Tutorials Python Numpy.sqrt() - Square Root

June 30, 2021 How to Split a list into N Parts in Python

May 12, 2021 Python: Get the Maximum value in a NumPy Array

June 09, 2021 How to Get List Shape in Python

June 11, 2021 How to Remove Element with JavaScript and jQuery

January 28, 2021 How to Remove Elements from Arrays in PHP

December 17, 2020