Run length of consecutive integers in array

12 views (last 30 days)
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
Azzi Abdelmalek on 15 Jun 2016
How can we test your data? post your data as a text instead of an image.

Sign in to comment.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 16 Jun 2016
v=[1949 4 5 57;1949 12 27 58;1950 7 8 275;1950 7 6 276 ;1950 7 3 277 ]
a=v(:,end)
id=[0;diff(a)]==1
ii1=strfind(id',[0 1])
ii2=strfind([id' 0],[1 0])
ii=ii2-ii1
for k=1:numel(ii)
ix=ii2(k);
out{k,1}=sprintf('date %d %d %d Run Length: %d',[v(ix,1:3) ii(k)])
end

More Answers (1)

dpb
dpb on 15 Jun 2016
ix=find(diff(v)~=1); % indices
rl=diff([0; ix]); % runlength
  2 Comments
dpb
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
>>

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices 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!