필터 지우기
필터 지우기

counting & indexing sequences of consecutive integers

조회 수: 2 (최근 30일)
Dean Ranmar
Dean Ranmar 2017년 3월 21일
편집: Jan 2017년 3월 21일
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
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.
Dean Ranmar
Dean Ranmar 2017년 3월 21일
Sorry! My question is: is there a way to re-write the difference function (Idiff) OR a way to use it to get my desired results (#1-3 as shown) without having to resort to adding 1 to the last Ldx value? (You're right that I'm bothered by it not being 'ideal.') I thought maybe someone could improve on what I have. Thanks.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 3월 21일
편집: Jan 2017년 3월 21일
With FEX: RunLength (if you have problems compiling the C-Mex file, use RunLength_M instead):
[B, N, Pos] = RunLength(diff(samp));
conseq = (B == 1);
Number = sum(conseq)
Index = Pos(conseq)
Length = N(conseq) + 1

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by