Eli Borodach Eli Borodach - 5 months ago 13
Python Question

How to multiply element by element between Matrices in PYTHON

Let's assume I have 2 matrices which each of them represents vector:

X = np.matrix([[1],[2],[3]])
Y = np.matrix([[4],[5],[6]])


I want the output to be the result of multiplying it element by element, which means it should be:

[[4],[10],[18]]


Notice: it is np.matrix and not np.array

10x in advance

Answer

so remember that NumPy matrix is a subclass of NumPy array, and array operations are element-wise.

therefore, you can convert your matrices to NumPy arrays, then multiply them with the "*" operator, which will be element-wise:

>>> import numpy as NP
>>> X = NP.matrix([[1],[2],[3]])
>>> Y = NP.matrix([[4],[5],[6]])

>>> X1 = NP.array(X)
>>> Y1 = NP.array(Y)

>>> XY1 = X1 * Y1
     array([[ 4],
            [10],
            [18]])

>>> XY = matrix(XY1)
>>> XY
 matrix([[ 4],
         [10],
         [18]])

alternatively you can use a generic function for element-wise multiplication:

>>> a = NP.matrix("4 5 7; 9 3 2; 3 9 1")
>>> b = NP.matrix("5 2 9; 8 4 2; 1 7 4")

>>> ab = NP.multiply(a, b)
>>> ab
  matrix([[20, 10, 63],
          [72, 12,  4],
          [ 3, 63,  4]])

these two differ in the return type and so you probably want to choose the first if the next function in your data flow requires a NumPy array; if it requires a NumPy matrix, then the second

Comments