1

My 3d array has shape (3, 2, 3), my 2d array is (2, 3). The multiplication i want to conduct is np.dot(2d, 3d[i,:,:].T) so it should return a result with shape (3, 2, 2). I could write a loop, but it is not the most efficient way, I have read there is an operation called np.tensordot, but would it work for my case? If yes, how would it work?

NiKS
  • 377
  • 3
  • 15
  • Does this answer your question? [Numpy multiply 3d matrix by 2d matrix](https://stackoverflow.com/questions/50796440/numpy-multiply-3d-matrix-by-2d-matrix) – CDJB Nov 15 '19 at 14:32

2 Answers2

2

We can use np.einsum -

# a, b are 3D and 2D arrays respectively
np.einsum('ijk,lk->ilj', a, b)

Alternatively, with np.matmul/@-operator on Python3.x -

np.matmul(a,b.T[None]).swapaxes(1,2)
Divakar
  • 212,295
  • 18
  • 231
  • 332
1

You can indeed use tensordot:

np.tensordot(a2D,a3D,((-1,),(-1,))).transpose(1,0,2)

or

np.tensordot(a3D,a2D,((-1,),(-1,))).transpose(0,2,1)

Disadvantage: as we have to shuffle axes in the end the result arrays will be non-contiguous. We can avoid this using einsum as shown by @Divakar or matrix multiplication if we do the shuffling before multiplying, i.e:

a2D@a3D.transpose(0,2,1)
Paul Panzer
  • 49,838
  • 2
  • 44
  • 91