MATLAB: Finding sequences and choose first one from that sequence

findpatternsequence

I have a matrix like this :
A=[1 7; 1 8; 2 2; 2 3; 2 4; 2 8; 4 3; 4 4; 4 5; 4 6];
I want to find a matrix (say B) from A as like bellow:
B= [1 7; 2 2; 2 8; 4 3];
That means, if there is a sequence (not sure if this si the exact word to describe the problem!) in the second column of A, then I want only first element of this sequence. For example: I have 1 7 and 1 8 in A..so I want 1 7. Similarly; I have 2 2; 2 3; 2 4; 2 8..so from here I want 2 2 and 2 8. Finally, for 4 3; 4 4; 4 5; 4 6–I want 4 3.

Best Answer

I agree, it was a bit confusing at first. Group by the first column and then by the max of the diff of values in the second column or 1.
To handle the case where there is a single row in a group ([2,8]), I had to specify min as an anonymous fxn so that I could specify the direction.
A=[1 7; 1 8; 2 2; 2 3; 2 4; 2 8; 4 3; 4 4; 4 5; 4 6];
G = findgroups(A(:,1),[1;max(1,diff(A(:,2)))])
f = @(x) min(x,[],1)
B = splitapply(f,A,G)
B = 4×2
1 7
2 2
2 8
4 3