Longest segment of successive numbers of a sequence

1 view (last 30 days)
If I have a vector
[ 1 2 7 8 3 9 4 7 2 5 7 8 9]
I want to find the longest segment of 'successive' numbers in this sequence.
In this example, the sequences would be:
[1 2 7 8], [3 9], [4 7], [2 5 7 8 9]
So the answer in this case will be
[2 5 7 8 9]
How can I do this using inbuilt matlab functions, and no for loops?
  2 Comments
math123
math123 on 16 Oct 2017
The sequences are going from smallest to largest, so if the vector was [1 3 1 5] the sequences would be [1 3] [1 5], does that make sense?

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 16 Oct 2017
>> V = [1,2,7,8,3,9,4,7,2,5,7,8,9];
>> D = [0,find([diff(V)<0,true])];
>> [~,X] = max(diff(D));
>> V(D(X)+1:D(X+1))
ans =
2 5 7 8 9

More Answers (1)

Jan
Jan on 16 Oct 2017
Edited: Jan on 16 Oct 2017
a = [ 1 2 7 8 3 9 4 7 2 5 7 8 9];
ind = find([true, a(2:end) < a(1:end-1), true]);
len = diff(ind);
[maxLen, p] = max(len);
longest = a(ind(p):ind(p + 1) - 1)

Community Treasure Hunt

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

Start Hunting!