Number of sequences with 3 or more ascending numbers
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Matt J
2020-4-6
all( diff(v(k:k+2)) >= 0 )
2 个评论
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
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!