Run length of consecutive integers in array

8 次查看(过去 30 天)
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

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2016-6-16
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

更多回答(1 个)

dpb
dpb 2016-6-15
ix=find(diff(v)~=1); % indices
rl=diff([0; ix]); % runlength
  2 个评论
dpb
dpb 2016-6-16
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
>>

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by