-1

Does anyone know of a way to do an elementwise dot product with numpy?

import numpy as np
a = np.array([ [0,0,0],[0,0,1] ])
b = np.array([ [1,2,3],[1,3,2] ])
for i in range(0, size(a)):
    c.append(np.dot(a[i],b[i]))

and I want c = [0,2] Also how would you about making a sequence of integers scalarly multiply a vector? So: a = [1,2] b = [0,1,0] Let the operation be oper oper(a,b) the result should be c = [[0,1,0],[0,2,0]] Thanks in advance

1 Answers1

1

Your code actually performs i) element-wise multiplication ii) summing across the second dimension, which boils down to a one-liner. Example:

In [1]: import numpy as np

In [2]: a = np.array([ [0,0,0],[0,0,1] ])

In [3]: b = np.array([ [1,2,3],[1,3,2] ])

In [4]: (a * b).sum(axis=1)
Out[4]: array([0, 2])

Your second operation is called an outer product, you could do it in several ways:

In [1]: import numpy as np

In [2]: a=np.array([1,2])

In [3]: b=np.array([0,1,0])

In [4]: a[:, None] * b
Out[4]: 
array([[0, 1, 0],
       [0, 2, 0]])

In [5]: np.outer(a, b)
Out[5]: 
array([[0, 1, 0],
       [0, 2, 0]])
maousi
  • 46
  • 1
  • 4
  • For the second operation, you can also use `np.tensordot(a, b, axes=0)` –  Jun 27 '22 at 16:56