diff
Differences between adjacent elements.
Syntax
Section titled “Syntax”Y = diff(X)Y = diff(X, n)Y = diff(X, n, dim)Description
Section titled “Description”Returns the first-order difference of X: a vector or array of X(i+1) - X(i) along the first non-singleton dimension. The result has one fewer element along that dimension.
With n, returns the n-th order difference (recursive application of first-order). With dim, takes differences along the specified dimension.
Useful for numerical differentiation, detecting changes in a signal, and discrete approximations to derivatives.
Examples
Section titled “Examples”diff([1 3 6 10 15]) % [2 3 4 5]diff([1 4 9 16 25], 2) % [2 2 2] second differences (constant for x²)diff(magic(3), 1, 2) % first differences along columns (per row)