How to calculate the difference between elements x[i+1] and x[i-1]?

Viewed 142

Given an array A, with size n, I want a function that returns an array R with size n-2 such that R[i] = A[i+1] - A[i-1].

I tried to check the options of numpy.diff but apparently it only calculates the difference between consecutive elements, i.e., A[i+1] - A[i].

3 Answers

You can directly subtract the slices of the first n-2 values from the last n-2 values, or vice versa:

>>> r = numpy.array([1, 2, 3, 4, 5, 6])
>>> r[2:], r[:-2]
(array([3, 4, 5, 6]), array([1, 2, 3, 4]))
>>> r[:-2] - r[2:]   # r[i] = r[i-1] - r[i+1]
array([-2, -2, -2, -2])
>>> r[2:] - r[:-2]   # r[i] = r[i+1] - r[i-1]
array([2, 2, 2, 2])

Both slicing and element-wise subtraction are performed by numpy and thus have minimal overhead.

I would write a small function that does this:

def diff(A):
    R = []
    for i in range(1,len(A)-1):
        R.append(A[i+1]-A[i-1])
    return R

Or using a list comprehension:

R = [A[i+1] - A[i-1] for i in range(1,len(A)-1]

I would go with:

numpy.diff(r[1:])+numpy.diff(r[:-1])
Related