Finding consecutive values in a vector

9 views (last 30 days)
Peter Wang
Peter Wang on 7 Sep 2020
Commented: Bruno Luong on 8 Sep 2020
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 Comment
Peter Wang
Peter Wang on 7 Sep 2020
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.

Sign in to comment.

Answers (1)

Matt J
Matt J on 7 Sep 2020
Edited: Matt J on 7 Sep 2020
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 Comments
Image Analyst
Image Analyst on 7 Sep 2020
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 on 8 Sep 2020
Agree with Image Analyst. The question is unclear.

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!