[TOC]

diff

Difference

Usages

Y = diff(X)

Y = diff(X, n)

Y = diff(X, n, dim)

Examples

Input
Y = diff(1:10)
Output
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
Input
% Original 3 x 4 matrix.
A = rand(3,4);

% 1st order differences. 
% It is applied to the first dimension.
% The output is a 2 x 4 matrix.
diff(A,1)

% 2nd order differences. 
% The 1st dimension is non-singleton.
% Thus, it calculates the differences along the 1st dimension.
% After that, it becomes a 2 x 4 matrix.
% The 1st dimension of this 2 x 4 matrix is again non-singleton.
% Thus, it calculates the differences along the 1st dimension again.
% The final output is a row vector of 4 elements.
diff(A,2)

% It gives the same result as applying diff 2 times.
diff(diff(A))
Output
ans = 1e-1 × 
-4.7459   1.4206  -1.5446   7.0858
-0.5799   6.5388   0.1692  -6.4966

ans = 
 0.4166   0.5118   0.1714  -1.3582

ans = 
 0.4166   0.5118   0.1714  -1.3582
Input
% Input
A = rand(3,4)

% 2nd order differences along the first dimension.
diff(A,2,1)

% The above is the same as the following,
% in which diff() is applied to the first dimension two times.
diff(diff(A,1,1),1,1)
Output
A = 1e-1 × 
 7.1917   2.1540   2.9677   6.1616
 8.2308   0.6028   8.4035   8.5812
 3.1568   5.3801   4.9360   0.1907

ans = 
-0.6113   0.6329  -0.8903  -1.0810

ans = 
-0.6113   0.6329  -0.8903  -1.0810
Input
% Original 3 x 4 matrix.
A = rand(3,4);

% 1st order differences along the first dimension.
% The output is 2 x 4.
diff(A,1,1)

% 2nd order differences along the first dimension.
% The output is 1 x 4.
diff(A,2,1)

% 3rd order differences.
% Since 3 >= size(X,1), it returns an empty matrix.
diff(A,3,1)
Output
ans = 1e-1 × 
 6.8987   4.7845  -2.0000   1.4139
-8.6064  -1.7525  -1.6810   2.2826

ans = 
-1.5505  -0.6537   0.0319   0.0869

ans =
 [] (double array)