Math244
Math244

Reputation: 165

Max Series of Consecutive Numbers

I need help finding a way to do this, although it seems as it should be pretty simple. Lets say I have a nx1 array. For example, let X=[1 1 1 .5 .4 .2 -.2 -.3 1 1 0 1]. What I am trying to do is find where the greatest series of consecutive 1's begins and how many 1's are in it. For instance, using X, the greatest series of consecutive series starts at the index 1 and is of length 3. Also, I will be using very large sets of data so I would like to try and find the most efficient and fastest way this can be done.

Upvotes: 1

Views: 278

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

A function like this can help

function [start, len] = findLongestRunning(x)
y = find(diff([0;x(:)==1;0]));
[len,J] = max(y(2:2:end)-y(1:2:end));
start = y(2*J(1)-1);
end

Running on your example

>> [start, len] = findLongestRunning(x)
start =
     1
len =
     3

Note that the code returns the first occurence if there are more than one sequence meeting the requirements:

>> [start, len] = findLongestRunning([x 0 x])
start =
     1
len =
     3

Upvotes: 0

horchler
horchler

Reputation: 18484

Here's one way that you could accomplish that fairly efficiently:

x = [1 1 1 0.5 0.4 0.2 -0.2 -0.3 1 1 0 1];
x1 = (x==1);
d = diff(x1(:).');
start = find([x1(1) d]==1)
len = find([d -x1(end)]==-1)-start+1

which returns

start =

     1     9    12

len =

     3     2     1

Upvotes: 2

Related Questions