grokkaine - 1 year ago 83

Python Question

How to compute a xi-xj matrix in numpy without loops (by api calls)?

Here's what to start with:

`import numpy as np`

x = np.random.rand(4)

xij = np.matrix([xi-xj for xj in x for xi in x]).reshape(4,4)

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

Answer Source

By reshaping the array, you can use the minus operator to calculate what you want

```
import numpy as np
x = np.random.rand(4)
x = x.reshape(-1,1)
xij = np.matrix(x.T - x)
```

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