0

it might be ansewred before but I couldn't find the answer. lets say I have two matices:

A = [[1,2,3],
     [4,5,6]]
B = [[1,2,3]
     [4,5,6]]

and I want to multiply them element by element, for example element of index [0,0] form A with [0,0] from B, [0,1] A with [0,1] B,... etc. and at the end i would get a matrix like the below:

C = [[1,4,9]
     [16,25,36]]

i know I can do it using for loop, but is there a function that could this for me, I need it to be faster than the loop. Thanks

asem assaf
  • 11
  • 1
  • 5
  • Similar question, but for Numpy specifically: https://stackoverflow.com/questions/40034993/how-to-get-element-wise-matrix-multiplication-hadamard-product-in-numpy – D Malan Aug 17 '20 at 11:24

2 Answers2

2

Simply use numpy.multiply

A = np.array([[1,2,3],
     [4,5,6]])


B = np.array([[1,2,3],
     [4,5,6]])

np.multiply(A,B)

array([[ 1,  4,  9],
       [16, 25, 36]])
Darth Vader
  • 881
  • 2
  • 7
  • 24
0

You may just use numpy multiplication.

A = np.array([[1,2,3],[4,5,6]])
B = np.array([[1,2,3],[4,5,6]])
C = A*B
Out:
[[ 1  4  9]
 [16 25 36]]
Fallen Apart
  • 723
  • 8
  • 20