Joker
Joker

Reputation: 81

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

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!

Upvotes: 2

Views: 383

Answers (3)

en_lorithai
en_lorithai

Reputation: 1260

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.

Upvotes: 1

Alex
Alex

Reputation: 161

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

Upvotes: 0

Ehsan
Ehsan

Reputation: 12397

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

Upvotes: 4

Related Questions