counting & indexing sequences of consecutive integers
1 view (last 30 days)
Show older comments
Given a vector of ordered (increasing) integers, I want to identify each sequence of consecutive integers & count them. Thus, I want to extract three pieces of information from any such vector:
1) the number of sequences of consecutive integers; 2) the starting indices [in the original vector] of the sequences; 3) the length of each sequence.
The below code works but I had to include the step "Ldx(end) = Ldx(end) + 1" to make it work because the difference function I created (Idiff) gives a duplicate value at the end instead of the 'next' [non-existent] index, which would be ideal. (I included the step "Idx = Idx(1:end-1)" here to rid myself of the extra difference value but it's unnecessary; I get the number of sequences (ndx) from the Ldx vector and I can just ignore that last value in Idx.)
I've included two sample vectors for anyone who wants to try this out. Have fun.
_________________
% First: define a necessary "differencing" function
x = []'; Idiff = @(x) [1; find(diff(x)-1)+1; length(x)];
samp = [11 13 14 15 16]'; smp2 = [11 13 14 15 16 20]';
Idx = Idiff(samp); Ldx = diff(Idx); Ldx(end) = Ldx(end) + 1; Idx = Idx(1:end-1); ndx = length(Ldx);
Id2 = Idiff(smp2); Ld2 = diff(Id2); Ld2(end) = Ld2(end) + 1; Id2 = Id2(1:end-1); nd2 = length(Ld2);
2 Comments
Adam
on 21 Mar 2017
What is the question you are asking exactly? You seem to have just posted code that you say works even if it isn't 100% ideal.
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!