user3.14259
user3.14259

Reputation: 111

Finding the size of the longest sequence of consecutive numbers in a random array of size 1xn using matlab

I would like to find the size of the longest sequence of consecutive numbers in a random array of size 1xn using Matlab. I know that there are two ways to do this: 1) using a loop and 2) using Matlab functions e.g. find, but I am unsure about how to do this without using both?

E.G. [1 2 3 5 8 9 10 11 12 13 14 17]

The longest sequence in this would be 10 11 12 13 14, which would be of size 5.

I tried this but it doesn't work:

function [start, finish] = longest(sequence)

x = diff(t)==1;

f = find([false,x]~=[x,false]);

g = find(f(2:2:end)-f(1:2:end-1)>=N,1,'first');

Upvotes: 0

Views: 262

Answers (1)

craigim
craigim

Reputation: 3914

Your variables don't match, but assuming that all(t == sequence) you are on the right track. You want to distinguish between the start of each run and the end by doing a second diff.

% Mark all sequences
x = diff(sequence) == 1;

% Take the second derivative to find the edges
xx = diff([false, x, false]);

% This gives matched pairs of indexes for each block
initial = find(xx == 1);
final = find(xx == -1);

% Get the block length
blockLength = final - initial;

% Get the max length
[~, idx] = max(blockLength);

% Return the indices
start = initial(idx);
finish = final(idx);

The result on your test gives start = 5, finish = 11. If you want to also return the block length, replace the ~ with your variable name

Upvotes: 1

Related Questions