Zanam - 15 days ago 8

Python Question

I have matrix A of dimension

`500x2000x30`

`30x5`

You can think that there are 500 instances of

`2000x30`

`500x2000x30`

I want to multiply each of

`1x2000x30`

`1x2000x5`

i.e.

`A X B`

`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])`

Source (Stackoverflow)

Comments