Search code examples
pythonnumpygradient

Gradient for array elements being more than one element apart


Is it possible to take the gradient between two points that are more than one element apart?

A simple array:

f = np.array([4,5,8,1,5,3,2,5])

I want to program the following:

  • At boundaries: One-sides as used by np.gradient

  • Values next to boundary values: Central differences as used by np.gradient for interior points

  • For the interior points

    ((i-2)-(i+2))/4

The resulting arry:

f_res = np.array([1,2,0.25,-0.5,-1.5,1,1,3])

Documentation for np.gradient: numpy.gradient


Solution

  • You could easily compute this manually:

    N = 2
    out = np.gradient(f)
    out[N:-N] = (f[2*N:]-f[:-2*N])/4
    

    Output:

    array([ 1.  ,  2.  ,  0.25, -0.5 , -1.5 ,  1.  ,  1.  ,  3.  ])