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 个)
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
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?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!