Finding consecutive values in a vector

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