Run length of consecutive integers in array

11 ビュー (過去 30 日間)
Tyler Smith
Tyler Smith 2016 年 6 月 15 日
コメント済み: dpb 2016 年 6 月 16 日
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 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 6 月 15 日
How can we test your data? post your data as a text instead of an image.
Tyler Smith
Tyler Smith 2016 年 6 月 16 日
attached is a .mat file of the data.

サインインしてコメントする。

採用された回答

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 件のコメント
Tyler Smith
Tyler Smith 2016 年 6 月 16 日
Thanks so much!

サインインしてコメントする。

その他の回答 (1 件)

dpb
dpb 2016 年 6 月 15 日
ix=find(diff(v)~=1); % indices
rl=diff([0; ix]); % runlength
  2 件のコメント
Tyler Smith
Tyler Smith 2016 年 6 月 16 日
Thank you!
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 Center および File ExchangeTime Series Objects についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by