Number of sequences with 3 or more ascending numbers

6 visualizaciones (últimos 30 días)
Avish Sjavi
Avish Sjavi el 6 de Abr. de 2020
Comentada: Matt J el 6 de Abr. de 2020
Hello,
I have following problem:
I have to find number of sequences occuring in vector. Such sequence contains 3 or more numbers which are ascending
so, for examplet
v = [ 1 8 2 5 8 0 0 1 2 3 4 9]
in this vector, such sequence occurs 2 times: 2 5 8 AND 0 1 2 3 4 9.
I would like to have these sequences stored in separate vector.
So far i have tried this:
v = [ 1 8 2 5 8 0 0 1 2 3 4 9]
n_sequences=0
for k = 1:length(v)
if v(k)<v(k+1)<v(k+2)<v(k+3)
n_sequences= n_sequences + 1
end
end
However this doesnt work as I supposed. I am not sure how to incorporate "3 OR MORE" into code.
Thanks,

Respuestas (2)

Matt J
Matt J el 6 de Abr. de 2020
all( diff(v(k:k+2)) >= 0 )
  2 comentarios
Avish Sjavi
Avish Sjavi el 6 de Abr. de 2020
Thanks, but i am not sure how to incorporate this to my code
Matt J
Matt J el 6 de Abr. de 2020
It tests whether you have 3 increasing elements in a row, as you asked for. Examples:
>> v = [ 1 8 2 5 8 0 0 1 2 3 4 9]
v =
1 8 2 5 8 0 0 1 2 3 4 9
>> k=3;
>> all( diff(v(k:k+2)) >= 0 )
ans =
logical
1
>> k=4;
>> all( diff(v(k:k+2)) >= 0 )
ans =
logical
0
>> k=6;
>> all( diff(v(k:k+2)) >= 0 )
ans =
logical
1

Iniciar sesión para comentar.


Andrei Bobrov
Andrei Bobrov el 6 de Abr. de 2020
lo = diff(v) > 0;
lo = [~lo(1);lo];
lo2 = [lo(2:end);false]|lo;
i = cumsum(lo == 0 & lo2).*lo2;
j = accumarray(i + 1,1);
C = accumarray(i + 1,(1:numel(v))',[],@(x){v(x)});
out = C(J >= 3);

Categorías

Más información sobre Loops and Conditional Statements 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