0

Having two ndarrays, array d with shape (3,10,10) and array e with shape (3,10), how do I calculate the dot product of the first 10x10 matrix of d and the first row of e, the second 10x10 matrix of d and the second row of e, etc.

For example, having the following two arrays:

d = np.array([np.diag([1,1,1,1,1,1,1,1,1,1]), 
              np.diag([2,2,2,2,2,2,2,2,2,2]), 
              np.diag([3,3,3,3,3,3,3,3,3,3])])     
e = np.arange(30).reshape((3,10))

How do I calculate the 3x10 array:

array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
       [60, 63, 66, 69, 72, 75, 78, 81, 84, 87]])

I tried using np.dot and np.tensordot and also transposing and adding a new axis to e before doing so, but I coulnd't figure out how to solve this problem.

Alex R
  • 3,139
  • 1
  • 18
  • 28

1 Answers1

2

We can use np.einsum -

np.einsum('ijk,ij->ik',d,e)

Play around with its optimize flag to use BLAS.

Or np.matmul -

np.matmul(d,e[...,None])[...,0]

Note : On Python 3.x np.matmul could be replaced by @ operator.

Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Thank you! Do you know how this could possibly work using `np.tensordot`? I couldn't figure what my mistake was or if this even works using that function. – Alex R Oct 12 '19 at 13:26
  • 1
    @AlexR `tensordot` won't work because we need to keep the first axis off them aligned. Read here for more info - https://stackoverflow.com/questions/41870228/. – Divakar Oct 12 '19 at 13:27