piton_hunter - 2 months ago 24

Python Question

I have 2 matrices

`A`

`mxn`

`B`

`nxm`

`C`

`nxmxm`

`C[i]=A[:, i].dot(B[i, :])`

`A`

`B`

`A`

`B`

For example for such

`A`

`B`

`A = np.array([[1, 2, 3], [0, 1, -1]])`

B = np.array([[4, 5], [6, 7], [8, 9]])

I would like to have such matrix:

`C = np.array([[[4, 5], [0, 0]],`

[[12, 14], [6, 7]],

[[24, 27], [-8, -9]]])

Is it possible without cycles? If not, is it possible for case A = B.T?

Answer

You can use `np.einsum`

:

```
np.einsum('ij,jk->ijk', A, B)
array([[[ 4, 5],
[12, 14],
[24, 27]],
[[ 0, 0],
[ 6, 7],
[-8, -9]]])
```

From your comment:

```
np.einsum('ij,jk->jik', A, B)
```

will give you the desired shape of `C`