2

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 3

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

This conveniently uses the fact that the values in the excluded positions will be zero and will not impact on the sum. But suppose that there is a generic operation for which that is not the case. Is there a way that you can efficiently extract a 1-d array containing (in some order) the values of f[i]-f[j] only for the values of i,j for which i<j (i.e. length 21 in this example)?
@alani There are various ways to do that. Here is one: (f[:,None]-f)[np.triu_indices(f.size,1)]
@alani You are welcome :) Note that I even included the diagonal in the selection since diagonal in this specific case is 0. in a generic case, you can even choose the offset using the argument of either of those functions.
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.