How to calculate the difference between adjacent elements of a vector in Matlab and Octave
Use diff() function to calculate the difference between adjacent elements of a vector in Matlab and Octave
diff(v)
The parameter v is a vector with n elements.
The result is a vector with n-1 elements consisting of the difference between adjacent elements
Example
Create a numeric vector with 5 elements
>> v=[5, 3, 7, 1, 4]
Calculate the difference between adjacent elements
>> diff(v)
ans =
-2 4 -6 3
The result is a vector with 4 elements.
The elements of the new vector are the difference between the adjacent elements of the original vector.
$$ v(2)-v(1) = 3 - 5 = -2 \\ v(3)-v(2)= 7 - 3 = 4 \\ v(4)-v(3) = 1-7 = -6 \\ v(5)-v(4) = 4-1 = 3 $$