Home > Net >  Multiplying a Vector with a Tensor in numpy
Multiplying a Vector with a Tensor in numpy

Time:01-19

I‘m trying to optimize some code with a numpy. Currently I have the following code:

for i in range(0,bodies):
    delta_y = b@(k[:,i,:])
    delta_y *= dx
    y[i]  = delta_y
return y

where b is has the shape (5,) and k has the shape (5,3,4) is there a way to use a numpy multiplication instead of the for loop? I already tried plenty of thing and couldn’t solve the issue.

Currently I‘m trying:

B = np.repeat([b], y.shape[0], axis = 0)
delta_y= B.T@k
delta_y*= dx
y = delta_y

And getting an (5,5,4) shape instead of a (4,) shape.

CodePudding user response:

I figured out a solution, thanks to hpaulj:

delta_y = np.matmul(b,k.transpose(1,0,2))*dx
y  = delta_y
return y
  • Related