Finding consecutive values in a vector

조회 수: 14 (최근 30일)
Peter Wang
Peter Wang 2020년 9월 7일
댓글: Bruno Luong 2020년 9월 8일
Hi. I'm trying to find the consecutive values sorted in a vector and count the total number of the consecutive values. Here is what I have:
A = input('Enter a vector: ');
diff(find(diff([nan A nan])~=1));
% By entering the vector [1 2 3 4 4 4 3 2 1], the output would be
% ans =
% 4 1 1 1 1 1
The reason I'm stuck is that my code only works for increment vectors([1 2 3 4]), but not for identical([4 4 4]) or decrement vectors([4 3 2 1]). Any suggestions or hints will be of great help to me.
  댓글 수: 1
Peter Wang
Peter Wang 2020년 9월 7일
I've tried both
diff(find(diff([nan A nan])~=-1|0|1))
and
diff(find(diff([nan A nan])~=-1&0&1))
However neither of them worked.

댓글을 달려면 로그인하십시오.

답변 (1개)

Matt J
Matt J 2020년 9월 7일
편집: Matt J 2020년 9월 7일
Here's a way to do it using group1s from the File Exchange
A=[1 2 3 4 4 4 3 2 1 0 1 2 3 4 5];
D=diff([0,A])==1;
G=group1s(D);
G(~G)=max(G)+1:max(G)+nnz(~G);
s=splitapply(@numel,G,G);
clear result;
result=s(unique(G,'stable'))
result =
4 1 1 1 1 1 1 5
  댓글 수: 3
Image Analyst
Image Analyst 2020년 9월 7일
Yeah, what do you do in a situation like this? The 0 could be a member of the consecutive decreasing sequence (4,3,2,1,0) but also a member of the increasing sequence (0,1,2,3,4,5). So do you want to count the 0 twice -- once in each group? Or just in the first group? So would the result be
4 for the 1,2,3,4
1 for going from the first 4 to the second 4 which doesn't increase or decrease by 1
1 for going from second 4 to the third 4 which doesn't increase or decrease by 1
5 for the decreasing sequence [4,3,2,1,0] (which starts with the third 4)
6 for the increasing sequence [0,1,2,3,4,5] or 5 if you didn't want to include the 0 again.
So that would give a result of [4,1,1,5,6].
I guess, Peter, we'd need a better explanation of your rules. Also, can we assume that the numbers area strictly integers, and that this is not your homework?
I don't understand why you said
A = input('Enter a vector: ');
diff(find(diff([nan A nan])~=1));
% By entering the vector [1 2 3 4 4 4 3 2 1], the output would be
% ans =
% 4 1 1 1 1 1
I can see the first 4, and maybe two of the 1's, but since the tail end of the vector was [4,3,2,1] (4 consecutive numbers) and your code was clearly trying to allow for differences of -1 as well as +1, why is there not a 4 as the last element of your answer?
Bruno Luong
Bruno Luong 2020년 9월 8일
Agree with Image Analyst. The question is unclear.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by