diff

diff(arr)

diff(arr, dim)

Create a new matrix or array with the difference of the passed matrix or array.

Dim parameter is optional and used to indicate the dimension of the array/matrix to apply the difference

If no dimension parameter is passed it is assumed as dimension 0

Dimension is zero-based in javascript and one-based in the parser

Arrays must be 'rectangular' meaning arrays like [1, 2]

If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays

Try it yourself:

See also:

diff(): Differences Between Successive Values

diff() calculates successive differences in an array or matrix dimension. Given [3, 7, 12], it produces [4, 5], revealing how the series changes from one observation to the next. This is a discrete difference, not a symbolic derivative.

Reading changes in data

Difference sequences are useful for trend analysis, increments, rates, and preprocessing time-series data. Apply diff again to obtain second differences, which can reveal changing acceleration or quadratic patterns. Use cumsum() to rebuild a sequence from changes when the initial value is known.

diff shortens the chosen dimension by one, so an input with fewer than two entries cannot yield an ordinary adjacent difference. Check shape with size(), and do not assume the result aligns index-for-index with the original data. If you need a direct subtraction of two corresponding arrays, use subtract().

Discrete versus continuous change

For a mathematical derivative of an expression, use derivative(). diff instead reflects actual sampling intervals; divide by the interval length with divide() when approximating a rate of change.

All functions