MATLAB: How to use cells in loop, and output a new column vector.

cell arrayscolumnexcelvector

I'm relatively new to matlab, and have been using it to read in and plot values in microsoft excel. Let's say the format of the data I have looks like two column vectors, which look like:
x={1;2;3;4;8;12;16;20}
y={3;2;1;4;5;4;3;7}
What I would like to do is incrementally take the difference between consecutive y points, and if the difference is greater than 2, then it should take the difference between the final x value in that increment, and the first, then reset and continue reading down the column.
For example, in the two column vectors above, I would like to take incremental differences in y, which would look like:
y_difference={(2-3) (1-2) (4-1) %Next Increment

(4-5) (3-4) (7-3)}
y_difference={-1 -1 3 %Next Increment
-1 -1 4}
So the resulting x outputted values would be
x_output={(4-1) (20-8)}
x_output={3 12}
I'm not sure if it's possible to reset the loop after every difference greater than 2, or how to output it as a column vector, but I'd figure it'd be worth a shot to ask.
Thanks!

Best Answer

% Define input vectors. (I used numeric arrays, not cell arrays. Convert if needed.)
x=[1;2;3;4;8;12;16;20];
y=[3;2;1;4;5;4;3;7];
% Find the location of the greater-than-two increments in y
idx = find(diff(y)>2);
% Using those anchor points, subtract the appropriate elements of x
x_output = x(idx+1) - [x(1);x(idx(1:end-1)+2)]