Run length of consecutive integers in array
Show older comments
I am working with an array and need to determine the run length of consecutive integers in the 4th column of the array. Here is a sample from my data:

In the 4th column, where the numbers increase by 1, I want to determine the amount of times they consecutively increase by 1 and output to another variable. So for the first two numbers I want an output run length of 2 since 58 and 59 are consecutive. The next 3 numbers (275,276,277) would produce a run length of 3. It needs to iterate all the way through the 4th column and produce a run length for all numbers that are consecutive. It would also be nice to take the date of the last number in the run length to be an index for each run length. Example for first 5 rows:
- Date: 1948 , 12 , 27 , Run Length: 2
- Date: 1950 , 3 , 4 , Run Length: 3
2 Comments
Azzi Abdelmalek
on 15 Jun 2016
How can we test your data? post your data as a text instead of an image.
Tyler Smith
on 16 Jun 2016
Accepted Answer
More Answers (1)
dpb
on 15 Jun 2016
ix=find(diff(v)~=1); % indices
rl=diff([0; ix]); % runlength
2 Comments
Tyler Smith
on 16 Jun 2016
dpb
on 16 Jun 2016
No problem but I'm curious why you'd choose the more complex of the two solutions? Because I left it to you to write the output expression and you didn't follow how to use the index array, mayhaps?
>> a=[y m d v];
>> ix=find(diff(a(:,end))~=1);
>> rl=diff([0; ix])
>> fprintf('Date: %d, %3d, %3d, Run Length: %2d\n',[a(ix,1:3) rl].')
Date: 1948, 12, 27, Run Length: 2
Date: 1950, 3, 4, Run Length: 3
Date: 1950, 11, 26, Run Length: 5
Date: 1950, 12, 11, Run Length: 4
>>
Categories
Find more on Time Series Objects 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!