Number of sequences with 3 or more ascending numbers

조회 수: 4 (최근 30일)
Avish Sjavi
Avish Sjavi 2020년 4월 6일
댓글: Matt J 2020년 4월 6일
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,

답변 (2개)

Matt J
Matt J 2020년 4월 6일
all( diff(v(k:k+2)) >= 0 )
  댓글 수: 2
Avish Sjavi
Avish Sjavi 2020년 4월 6일
Thanks, but i am not sure how to incorporate this to my code
Matt J
Matt J 2020년 4월 6일
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

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


Andrei Bobrov
Andrei Bobrov 2020년 4월 6일
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);

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by