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