Skip to content

diff

Difference

Y = diff(X)

  • X is an array of any number of dimensions.
  • It computes the following difference $$ y_i=x_{i+1}-x_i,\quad i=1,2,\ldots,N-1, $$ where x_i is the i-th element of an N-vector taken from X along the first non-singleton dimension, and y_i is the ith element of the output vector.
  • The output vector has N-1 elements.
  • If X is empty, Y will be empty.

Example 1: diff computes the differences along the first non-singleton dimension. In this case, it is the second dimension.

Y=diff(1:10)
Y =
Columns 1 through 4:
 1.000   1.000   1.000   1.000
Columns 5 through 8:
 1.000   1.000   1.000   1.000
Column 9:
 1.000

Y = diff(X, n)

  • X is an array of any number of dimensions.
  • n should be a real positive integer scalar, not equal to NaN or Inf.
  • It computes the n-th order differences $$ y_i=\sum^n_{i=0}\binom{n}{i}(-1)^{n-i}x_i,\quad i=1,2,\ldots,N-n, $$ where x_i is the i-th element of an N-vector taken from X along the first non-singleton dimension, and y_i is the ith element of the output vector.
  • The output vector has N-n elements.
  • It is the same as applying diff to the input X for n times. For instance diff(X,2) gives the same result as diff(diff(X)).
  • n can also be an empty matrix. In this case, it is the same as diff(X).

Example 2: Higher order differences.

% Original 3 x 4 matrix.
A=rand(3,4);

% 1st order difference. 2 x 4 matrix.
diff(A,1)

% 2nd order difference. 1 x 4 matrix.
diff(A,2)

% Since dimension one is now singleton, it works
% on the second dimension.
diff(A,3)

% It gives the same result as applying diff 3 times.
diff(diff(diff(A)))
ans = 1e-1 × 
 7.892  -2.707  -1.488   6.639
-8.041   0.512   2.962  -1.718

ans =
-1.593   0.322   0.445  -0.836

ans =
 1.915   0.123  -1.281

ans =
 1.915   0.123  -1.281

Y = diff(X, n, dim)

  • It is the same as applying diff(X, n), except that the differences are computed along the dim-th dimension.
  • dim should be a positive real integer scalar. If dim >= ndims(X), it computes the differences along a singleton dimension and therefore returns an empty matrix.
  • It gives an empty matrix if n >= size(X,dim).

Example 3: Higher order differences.

% Original 3 x 4 matrix.
A=rand(3,4);

% 1st order differences.
diff(A,1,1)

% 2nd order differences.
diff(A,2,1)

% Since n >= size(X,dim) below, it returns an empty matrix.
% This is different from calling diff(A,n), in which
% it would continue working on the first dimension, as
% in Example 2 above.
diff(A,3,1)
ans = 1e-1 × 
 9.545  -3.679  -2.729  -2.102
-1.944   3.499  -4.291  -3.276

ans =
-1.149   0.718  -0.156  -0.117

ans =
 Empty matrix