Tingiskhan - 1 year ago 106

Python Question

Assume that I have two arrays

`V`

`Q`

`V`

`(i, j, j)`

`Q`

`(j, j)`

`Q`

`V`

`(i, j, j)`

`i`

`import numpy as np`

v = np.random.normal(size=(100, 5, 5))

q = np.random.normal(size=(5, 5))

output = np.zeros_like(v)

for i in range(v.shape[0]):

output[i] = q.dot(v[i])

However, this is way too slow for my needs, and I'm guessing there is a way to vectorize this operation using either

`einsum`

`tensordot`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You can certainly use `np.tensordot`

, but need to swap axes afterwards, like so -

```
out = np.tensordot(v,q,axes=(1,1)).swapaxes(1,2)
```

With `np.einsum`

, it's a bit more straight-forward, like so -

```
out = np.einsum('ijk,lj->ilk',v,q)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**