Question

Suppose I have an array, and I want to compute differences between elements at a distance Delta. I can use numpy.diff(Array[::Delta-1]), but this will not give all possible differences (from each possible starting point). To get them, I can think of something like this:

for j in xrange(Delta-1):
    NewDiff = numpy.diff(Array[j::Delta-1])
    if j==0:
        Diff = NewDiff
    else:
        Diff = numpy.hstack((Diff,NewDiff))

But I would be surprised if this is the most efficient way to do it. Any idea from those familiar with the most exoteric functionalities of numpy?

Was it helpful?

Solution

The following function returns a two-dimensional numpy array diff which contains the differences between all possible combinations of a list or numpy array a. For example, diff[3,2] would contain the result of a[3] - a[2] and so on.

def difference_matrix(a):
    x = np.reshape(a, (len(a), 1))
    return x - x.transpose()

Update

It seems I misunderstood the question and you are only asking for an the differences of array elements which are a certain distance d apart.1)

This can be accomplished as follows:

>>> a = np.array([1,3,7,11,13,17,19])
>>> d = 2
>>> a[d:] - a[:-d]
array([6, 8, 6, 6, 6])

Have a look at the documentation to learn more about this notation.

But, the function for the difference matrix I've posted above shall not be in vain. In fact, the array you're looking for is a diagonal of the matrix that difference_matrix returns.

>>> a = [1,3,7,11,13,17,19]
>>> d = 2
>>> m = difference_matrix(a)
>>> np.diag(m, -d)
array([6, 8, 6, 6, 6])

1) Judging by your comment, this distance d is different than the Delta you seem to be using, with d = Delta - 1, so that the distance between an element and itself is 0, and its distance to the adjacent elements is 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top