counting & indexing sequences of consecutive integers

8 visualizaciones (últimos 30 días)
Dean Ranmar
Dean Ranmar el 21 de Mzo. de 2017
Editada: Jan el 21 de Mzo. de 2017
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 comentarios
Adam
Adam el 21 de Mzo. de 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.
Dean Ranmar
Dean Ranmar el 21 de Mzo. de 2017
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.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 21 de Mzo. de 2017
Editada: Jan el 21 de Mzo. de 2017
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

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by