Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Note that it is np.matrix and not np.array

like image 763
Eli Borodach Avatar asked Oct 25 '25 04:10

Eli Borodach


2 Answers

Tested np.multiply() on ipython and it worked like a charm

In [41]: X = np.matrix([[1],[2],[3]])

In [42]: Y = np.matrix([[4],[5],[6]])

In [43]: np.multiply(X, Y)

Out[43]: 
matrix([[ 4],
        [10],
        [18]])
like image 86
prashkr Avatar answered Oct 26 '25 18:10

prashkr


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

like image 26
doug Avatar answered Oct 26 '25 19:10

doug