# vector gradient of a raster image in R

I’m new to R and having trouble applying an equation that finds the vector gradient of a raster image. I understand the equation just fine, but still new enough to R to be confused on how to translate the equation into code. The equation is attached in an image below, where d is the distance between adjacent pixels, i and j are the horizontal and vertical unit vectors in the image plane, and x and y are the image coordinates. Φ represents the image.

Can anyone provide any advice on how to translate this into R to get the desired output?

Equation was taken from a 2004 publication, the pdf can be found here: http://seaice.alaska.edu/gi/publications/mahoney/Mahoney_2004_IGARSS_LandfastIce.pdf

For some raster `x` you can compute the two component rasters (to some constant of proportionality) this way:

``````igrad = focal(x, matrix(c(-1/2,0,1/2),ncol=3))
``````

(or maybe the other way round...)

These gradients are in raster units per raster cell width, so the constant of proportionality to get a true gradient is the cell width.

This works by using `focal` to get the difference between the adjacent cells left and right (or up and down) of any cell, which is what the parts in the numerators are.

Quick test with some simple data:

``````> x = matrix(1:12, ncol=3)
> x
[,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12
``````

The gradient in the across direction is 4 everywhere - look at the "6" cell and see it changes from 2 to 10 across a distance of 2 cell widths. The gradient in the up-down directions is 1 - again across the "6" cell the value changes from 5 to 7 in a distance of 2 units. Do we get that?

``````> as.matrix(focal(raster(x), matrix(c(-1/2,0,1/2),nrow=3)))
[,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]    1    1    1
[3,]    1    1    1
[4,]   NA   NA   NA
> as.matrix(focal(raster(x), matrix(c(-1/2,0,1/2),ncol=3)))
[,1] [,2] [,3]
[1,]   NA    4   NA
[2,]   NA    4   NA
[3,]   NA    4   NA
[4,]   NA    4   NA
``````

Yes we do. Note the NA values appear on the edge where you can't compute the gradient.