Numpy: Sum of 1D array for index i < j

Viewed 234

I'm trying to figure out how to most efficiently (with NumPy) calculate the following expression for a 1D ndarray (in this case, f):

enter image description here

I imagine I could do something like:

f = [ 1, 3, 2, 3, 7, 5, 2]
for i in range(0, len(f-1)):
    for j in range(0, len(f-2)):
        ...

But that would mean that I'll have to have a conditional loop for every element in the list, if I understand this correctly. Is there a better way to do this?

Thanks in advance for any tips!

3 Answers

You can leverage numpy broadcasting:

f = np.array([ 1, 3, 2, 3, 7, 5, 2])
np.triu(f[:,None]-f).sum()

or equally:

np.tril(f-f[:,None]).sum()

output:

-24

You could try this one

f = [ 1, 2, 3, 4]
combined = 0
for i in range(0, len(f)):
    for j in range(i+1, len(f)):
        combined += f[i]-f[j]

you use i as the starting point of your inner loop. This way you don't need the if conditions.

This doesn't use Numpy but if you want you could simply use list slicing and do something like this

def partial_sum(lst,i, j):
    return sum(lst[i:j])
Related