Zanam - 9 months ago 48
Python Question

# Multidimensional matrix multiplication in python

I have matrix A of dimension

500x2000x30
and matrix B of dimension
30x5
.

You can think that there are 500 instances of
2000x30
as matrix A is of dimension
500x2000x30
.

I want to multiply each of
1x2000x30
from A with matrix B to obtain new matrix of size
1x2000x5
.

i.e.
A X B
should give me a matrix of dimension
500x2000x5

Obviously looping 500 times through matrix A is a solution but is there an efficient way to achieve this?

Edit: Both A and B are numpy arrays

If you have numpy arrays you can use the np.dot function for this:
np.dot(A, B)

It will do exactly what you want, i.e. "contract" the last axis of A with the last axis of B:
 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])