MATLAB Function Reference | ![]() ![]() |
Differences and approximate derivatives
Syntax
Y = diff(X) Y = diff(X,n
) Y = diff(X,n
,dim)
Description
Y = diff(X)
calculates differences between adjacent elements of X
.
If X
is a vector, then diff(X)
returns a vector, one element shorter than X
, of differences between adjacent elements:
[X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]
If X
is a matrix, then diff(X)
returns a matrix of row differences:
[X(2:m,:)-X(1:m-1,:)]
In general, diff(X)
returns the differences calculated along the first non-singleton (size(X,dim) > 1
) dimension of X
.
Y = diff(X,
applies n
)
diff
recursively n
times, resulting in the nth difference. Thus, diff(X,2)
is the same as diff(diff(X))
.
Y = diff(X,
is the nth difference function calculated along the dimension specified by scalar n
,dim)
dim
. If order n
equals or exceeds the length of dimension dim
, diff
returns an empty array.
Remarks
Since each iteration of diff
reduces the length of X
along dimension dim
, it is possible to specify an order n
sufficiently high to reduce dim
to a singleton (size(X,dim) = 1
) dimension. When this happens, diff
continues calculating along the next nonsingleton dimension.
Examples
The quantity diff(y)./diff(x)
is an approximate derivative.
x = [1 2 3 4 5]; y = diff(x) y = 1 1 1 1 z = diff(x,2) z = 0 0 0
A = rand(1,3,2,4);
diff(A)
is the first-order difference along dimension 2
.
diff(A,3,4)
is the third-order difference along dimension 4
.
See Also
![]() | diary | dir | ![]() |