diff
Differences between adjacent elements.
Category: Language Fundamentals > Operators and Elementary Operations
Syntax
Y = diff(X)
Subtracts each element from the one after it along the first non-singleton dimension.
Y = diff(X, n)
Applies the difference n times, giving higher-order differences.
Y = diff(X, n, dim)
Takes differences along dimension dim.
Description
For a vector of length m, diff(x) has length m-1 and entries x(k+1) - x(k). Dividing by the spacing, diff(y) ./ diff(x), approximates the derivative of sampled data. For a matrix the differences run down each column.
If n is at least the length of the working dimension, the result is empty.
Input arguments
X- Numeric array.
n- Order of the difference. The default is 1.
dim- Dimension along which to differentiate.
Output arguments
Y- Differences. The working dimension is shorter by
nelements.
Example
x = [1 4 9 16 25];
diff(x)
diff(x, 2)
diff([1 2; 4 8; 9 9])
Output
ans = 1×4
3 5 7 9
ans = 1×3
2 2 2
ans = 2×2
3 6
5 1