MATLAB: Taking difference of adjecent elements by seting a custom order

diff command

Hi
I have the following vector:
[1 2 3 4 5 6]
I want to take the the difference between the third element and the first (3-1) and then fourth and second element (4-2) and so on. How do I do this?
Thank you!

Best Answer

Ali - you could create two vectors of indices that you can then use to perform the subtraction. One vector would be all indices starting from 3, 4, 5,... up to the last index (which would correspond to the length of the input vector), and the other vector would be all indices starting from 1, 2, 3,... up to two less than the end of the input vector. Try the following
A = [1 2 3 4 5 6];
idx2 = 3:length(A);
idx1 = 1:length(A)-2;
myDiff = A(idx2) - A(idx1);
Running the above returns
myDiff =
2 2 2 2
which correspond to the differences of 3-1, 4-2, 5-3, and 6-4.