Skip to content

diff

Differences between adjacent elements.

Y = diff(X)
Y = diff(X, n)
Y = diff(X, n, dim)

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.

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)
  • cumsum — Cumulative sum along a dimension.
  • sum — Sum elements of an array.