Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start/stop values for blocks of consecutive numbers

If I have a vector of:

[4,5,6,7,11,12,13,14,21,22,23]

How can I, without a loop, extract the start/end values of all consecutive number blocks i.e. the desired result for the above vector would be a 2-column vector:

b = 

4   7
11  14
21  23
like image 589
AnnaSchumann Avatar asked Dec 02 '15 11:12

AnnaSchumann


1 Answers

Another approach:

x = [4,5,6,7,11,12,13,14,21,22,23];
x = x(:);
ind = find([1; diff(x)-1; 1]);
result = [x(ind(1:end-1)) x(ind(2:end)-1)];
like image 62
Luis Mendo Avatar answered Sep 21 '22 16:09

Luis Mendo