I need to calculate the sum below where X is a matrix 2x5 and i/j is a selected column.

I've solved this with the following code, but I would like to know if there is an easier solution with numpy to solve this sum (without the for..range)
sum = 0
size = 5
for i in range(0, size):
for j in range(0, size):
if i != j:
sum = sum + np.power(np.linalg.norm(X[:, i] - X[:, j]), 2)
You can optimize quite a bit here. First, you only need to compute for off-diagonal elements of the full i-j matrix. Second, you can compute for just one half of the matrix and double the sum, since norm(a - b) == norm(b - a).
Use np.triu_indices (or np.tril_indices):
i, j = np.triu_indices(size, 1)
sum = 2 * (np.linalg.norm(X[:, i] - X[:, j], axis=0)**2).sum()
You can avoid the square roots (assuming you're using 2-norm):
sum = 2 * (X[:, i] - X[:, j])**2).sum(None)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With