# Is there a central difference/gradient function somewhere?

**URL:** <https://discourse.julialang.org/t/is-there-a-central-difference-gradient-function-somewhere/19454>\
**Category:** General Usage\
**Created:** [January 9, 2019, 10:30pm UTC](https://discourse.julialang.org/t/is-there-a-central-difference-gradient-function-somewhere/19454 "2019-01-09T22:30:27Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [January 10, 2019, 8:59am UTC](https://discourse.julialang.org/t/is-there-a-central-difference-gradient-function-somewhere/19454/3 "2019-01-10T08:59:11Z")

</div>

something like this?

```julia
function centraldiff(v::AbstractMatrix)
    dv = diff(v)/2
    a = [dv[[1],:];dv]
    a .+= [dv;dv[[end],:]]
    a
end

function centraldiff(v::AbstractVector)
    dv = diff(v)/2
    a = [dv[1];dv]
    a .+= [dv;dv[end]]
    a
end

```

These methods are of course not optimized for performance, writing the loop manually would likely improve performance and reduce memory allocations.

Note, these functions do not reduce the length of the input array (as `diff` does), by copying the first and last `diff` elements.

---

_[View the full topic](https://discourse.julialang.org/t/is-there-a-central-difference-gradient-function-somewhere/19454)._
