Number of sequences with 3 or more ascending numbers
3 views (last 30 days)
Show older comments
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,
0 Comments
Answers (2)
Matt J
on 6 Apr 2020
all( diff(v(k:k+2)) >= 0 )
2 Comments
Matt J
on 6 Apr 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
Andrei Bobrov
on 6 Apr 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);
0 Comments
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!