counting & indexing sequences of consecutive integers
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam
2017-3-21
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.
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!