gradient.RdDiscrete numerical gradient.
gradient(F, h1 = 1, h2 = 1)Returns the numerical gradient of a vector or matrix as a vector or matrix of discrete slopes in x- (i.e., the differences in horizontal direction) and slopes in y-direction (the differences in vertical direction).
A single spacing value, h, specifies the spacing between points in
every direction, where the points are assumed equally spaced.
If F is a vector, one gradient vector will be returned.
If F is a matrix, a list with two components will be returned:
numerical gradient/slope in x-direction.
numerical gradient/slope in x-direction.
where each matrix is of the same size as F.
TODO: If h2 is missing, it will not automatically be adapted.
x <- seq(0, 1, by=0.2)
y <- c(1, 2, 3)
(M <- meshgrid(x, y))
#> $X
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 0 0.2 0.4 0.6 0.8 1
#> [2,] 0 0.2 0.4 0.6 0.8 1
#> [3,] 0 0.2 0.4 0.6 0.8 1
#>
#> $Y
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1 1 1 1 1 1
#> [2,] 2 2 2 2 2 2
#> [3,] 3 3 3 3 3 3
#>
gradient(M$X^2 + M$Y^2)
#> $X
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 0.04 0.08 0.16 0.24 0.32 0.36
#> [2,] 0.04 0.08 0.16 0.24 0.32 0.36
#> [3,] 0.04 0.08 0.16 0.24 0.32 0.36
#>
#> $Y
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 3 3 3 3 3 3
#> [2,] 4 4 4 4 4 4
#> [3,] 5 5 5 5 5 5
#>
gradient(M$X^2 + M$Y^2, x, y)
#> $X
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 0.2 0.4 0.8 1.2 1.6 1.8
#> [2,] 0.2 0.4 0.8 1.2 1.6 1.8
#> [3,] 0.2 0.4 0.8 1.2 1.6 1.8
#>
#> $Y
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 3 3 3 3 3 3
#> [2,] 4 4 4 4 4 4
#> [3,] 5 5 5 5 5 5
#>
if (FALSE) { # \dontrun{
# One-dimensional example
x <- seq(0, 2*pi, length.out = 100)
y <- sin(x)
f <- gradient(y, x)
max(f - cos(x)) #=> 0.00067086
plot(x, y, type = "l", col = "blue")
lines(x, cos(x), col = "gray", lwd = 3)
lines(x, f, col = "red")
grid()
# Two-dimensional example
v <- seq(-2, 2, by=0.2)
X <- meshgrid(v, v)$X
Y <- meshgrid(v, v)$Y
Z <- X * exp(-X^2 - Y^2)
image(v, v, t(Z))
contour(v, v, t(Z), col="black", add = TRUE)
grid(col="white")
grX <- gradient(Z, v, v)$X
grY <- gradient(Z, v, v)$Y
quiver(X, Y, grX, grY, scale = 0.2, col="blue")
} # }