# gradient: Discrete Gradient (Matlab Style) In pracma: Practical Numerical Math Functions

## Usage

 `1` ```gradient(F, h1 = 1, h2 = 1) ```

## Arguments

 `F` vector of function values, or a matrix of values of a function of two variables. `h1` x-coordinates of grid points, or one value for the difference between grid points in x-direction. `h2` y-coordinates of grid points, or one value for the difference between grid points in y-direction.

## Details

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.

## Value

If `F` is a vector, one gradient vector will be returned.

If `F` is a matrix, a list with two components will be returned:

 `X` numerical gradient/slope in x-direction. `Y` numerical gradient/slope in x-direction.

where each matrix is of the same size as `F`.

## Note

TODO: If `h2` is missing, it will not automatically be adapted.

`fderiv`

## Examples

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33``` ```x <- seq(0, 1, by=0.2) y <- c(1, 2, 3) (M <- meshgrid(x, y)) gradient(M\$X^2 + M\$Y^2) gradient(M\$X^2 + M\$Y^2, x, y) ## Not run: # 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") ## End(Not run) ```

### Example output

```\$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

\$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

\$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

[1] 0.00067086
```

pracma documentation built on Dec. 11, 2021, 9:57 a.m.