0

I need a simple and fast function to multiply each row of numpy array 'a' to array 'b' a , b have same 2d dimention like the result of this is example(c): but I want a numpy function insted of this loop

a=np.arange(6).reshape(3,2)
b=np.arange(6,12).reshape(3,2)
c=np.array([[a[i,:]@b[i,:]]for i in range(a.shape[0])])
sacuL
  • 49,704
  • 8
  • 81
  • 106
user10482281
  • 53
  • 1
  • 5
  • I can't reproduce your arrays with your code, so I assumed you meant `a=np.arange(6).reshape(3,2)` and `b=np.arange(7,13).reshape(3,2)` – sacuL Nov 07 '18 at 16:02
  • You're right. then I edited the Q – user10482281 Nov 07 '18 at 16:06
  • To use `@` you have to tweak the dimensions a bit: `(a[:,None,:]@b[:,:,None])[:,0,:]`. Because at it's core `@` is designed to work with `n-2d` arrays. – hpaulj Nov 07 '18 at 16:14

1 Answers1

0

An easy way would be to write it yourself with vectorized numpy methods:

np.sum(a*b,axis=1,keepdims=True)

array([[  8],
       [ 48],
       [104]])
sacuL
  • 49,704
  • 8
  • 81
  • 106