1

I'd like to multiply each element of a 3D matrix with the element of a same-sized matrix at the same position.

In 2D it'd look like:

Is there any clean solution with numpy other than for loops ?

EDIT: This matrix operation is named "Hadamard product"

Jibsgrl
  • 95
  • 1
  • 9

2 Answers2

2

Just multiply them. numpy supports matrix operations.

x = np.arange(1, 10).reshape(3, 3)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
print(x*x)

All elements will be multiplied by the respective number.

array([[ 1,  4,  9],
       [16, 25, 36],
       [49, 64, 81]])
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
0

You can use simple * to to element-wise multiplication with numpy arrays.

a = np.array([[1,2],[3,4]])
b = np.array([[1,2],[3,4]])

print(a*b)

Will give you

[[ 1  4]
 [ 9 16]]
ywbaek
  • 2,971
  • 3
  • 9
  • 28