Zanam Zanam - 15 days ago 8
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

Answer

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:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:

 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
Comments