Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using numpy for the summation where i != j

Tags:

python

numpy

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

sum

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)
like image 866
ribs Avatar asked Feb 20 '26 15:02

ribs


1 Answers

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)
like image 144
Mad Physicist Avatar answered Feb 23 '26 06:02

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!