user10229833
user10229833

Reputation:

How do I multiply a 3D matrix and 2D matrix using numpy in Python?

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?

Upvotes: 2

Views: 1916

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

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:

[email protected](0,2,1)

Upvotes: 1

Divakar
Divakar

Reputation: 221564

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)

Upvotes: 3

Related Questions