Y = diff(X) calculates
differences between adjacent elements of X along
the first array dimension whose size does not equal 1:

If X is a vector of length m,
then Y = diff(X) returns a vector of length m-1.
The elements of Y are the differences between adjacent
elements of X.

Y = [X(2)-X(1) X(3)-X(2) ... X(m)-X(m-1)]

If X is a nonempty, nonvector p-by-m
matrix, then Y = diff(X) returns a matrix of size
(p-1)-by-m, whose elements are the differences between the rows of X.

Y = [X(2,:)-X(1,:); X(3,:)-X(2,:); ... X(p,:)-X(p-1,:)]

If X is a 0-by-0 empty matrix,
then Y = diff(X) returns a 0-by-0 empty matrix.

Y = diff(X,n) calculates
the nth difference by applying the diff(X) operator
recursively n times. In practice, this means diff(X,2) is
the same as diff(diff(X)).

Use the diff function to approximate partial derivatives with the syntax Y = diff(f)/h, where f is a vector of function values evaluated over some domain, X, and h is an appropriate step size.

For example, the first derivative of sin(x) with respect to x is cos(x), and the second derivative with respect to x is -sin(x). You can use diff to approximate these derivatives.

h = 0.001; % step size
X = -pi:h:pi; % domain
f = sin(X); % range
Y = diff(f)/h; % first derivative
Z = diff(Y)/h; % second derivative
plot(X(:,1:length(Y)),Y,'r',X,f,'b', X(:,1:length(Z)),Z,'k')

In this plot the blue line corresponds to the original function, sin. The red line corresponds to the calculated first derivative, cos, and the black line corresponds to the calculated second derivative, -sin.

Difference order, specified as a positive integer scalar or [].
The default value of n is 1.

It is possible to specify n sufficiently
large so that dim reduces to a single (size(X,dim)
= 1) dimension. When this happens, diff continues
calculating along the next array dimension whose size does not equal
1. This process continues until a 0-by-0 empty matrix is returned.

Dimension to operate along, specified as a positive integer
scalar. If no value is specified, the default is the first array dimension
whose size does not equal 1.

Consider a two-dimensional p-by-m input array, A:

diff(A,1,1) works on successive
elements in the columns of A and returns a (p-1)-by-m
difference matrix.

diff(A,1,2) works on successive
elements in the rows of A and returns a p-by-(m-1)
difference matrix.

Difference array, returned as a scalar, vector, matrix, or multidimensional
array. If X is a nonempty array, then the dimension
of X acted on by diff is reduced
in size by n in the output.