필터 지우기
필터 지우기

Run length of consecutive integers in array

조회 수: 8 (최근 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개)

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 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