grokkaine - 11 months ago 62

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)

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