# Gradient vector of a matrix of geographical extent

**URL:** <https://discourse.julialang.org/t/gradient-vector-of-a-matrix-of-geographical-extent/87318>\
**Category:** General Usage\
**Tags:** differentiation, calculus, gradient\
**Created:** [September 15, 2022, 3:39pm UTC](https://discourse.julialang.org/t/gradient-vector-of-a-matrix-of-geographical-extent/87318 "2022-09-15T15:39:26Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [September 15, 2022, 7:30pm UTC](https://discourse.julialang.org/t/gradient-vector-of-a-matrix-of-geographical-extent/87318/2 "2022-09-15T19:30:33Z")

</div>

You could adapt the 1D solution in the [post](https://discourse.julialang.org/t/differentiation-without-explicit-function-np-gradient/57784/2) linked to 2D as follows:

```julia
using Interpolations

f(x,y) = x^2 + y^2 # function used just to generate data

x = y = -2:0.02:2
z = f.(x, y') # z is the numeric data at coordinates (x, y)

itp = interpolate((x,y), z, Gridded(Linear()));
grad = gradient.(Ref(itp), x, y')

```

If the data matrix `z` is noisy, we could fit smoothing 2D splines before estimating the gradients. An example using Dierckx:

```julia
using Interpolations, Dierckx

f(x,y) = x^2 + y^2
x, y = -2:0.02:2, -3:0.02:3
nx, ny = length(x), length(y)
z = f.(x, y') + rand(nx, ny) # noisy data matrix over grid defined by (x,y)

s0 = 0.01*nx*ny*hypot(extrema(z)...) # test different smoothing factors
spl = Spline2D(x, y, z; kx=3, ky=3, s=s0)
zsmooth = evalgrid(spl, x, y)
itp = interpolate((x,y), zsmooth, Gridded(Linear()));
grad = gradient.(Ref(itp), x, y')

```

---

_[View the full topic](https://discourse.julialang.org/t/gradient-vector-of-a-matrix-of-geographical-extent/87318)._
