How to calculate the Hadamard product using Python NumPy?
We can use the numpy.multiply() function to calculate the Hadamard product using Python NumPy. We can use the following Python code for that purpose.
import numpy
m = 3
n = 4
A = numpy.random.randint(low=1, high=10, size=(m, n))
B = numpy.random.randint(low=1, high=10, size=(m, n))
H = numpy.multiply(A, B)
print("A: \n", A)
print("B: \n", B)
print("The Hadamard product of A and B: \n", H)
Here, we are creating two 3×4 matrices A and B. The elements of A and B are randomly generated using the numpy.random.randint() function. The generated integers will be within the range [low, high). And the size argument indicates the size of the matrix. For example, size=(m, n) specifies that the created matrix will have m rows and n columns.
Now, we are using the numpy.multiply() function to multiply the matrices A and B element-wise. So, H is the Hadamard product of A and B.
The output of the mentioned program will be:
A: [[6 1 1 7] [6 7 9 5] [6 3 6 1]] B: [[5 9 9 9] [2 6 5 7] [8 7 8 6]] The Hadamard product of A and B: [[30 9 9 63] [12 42 45 35] [48 21 48 6]]








































0 Comments