Counting consecutive occurences of 1s and -1s
2 次查看(过去 30 天)
显示 更早的评论
Hi, I have a vector containing -1,0 & 1. I want to count consecutive occurences of 1s & -1s.
If the input vector A = [0 0 1 1 1 1 0 0 0 -1 -1 -1 0 1 1 0 ], then I want an output which is Y = [4 -3 2]. (So the output vector is consecutive occurences of 1s and -1s with their sign).
Thanks
0 个评论
采纳的回答
Adam Danz
2019-5-2
编辑:Adam Danz
2019-5-2
The first step below counts all consecutive numbers. The second step eliminates the 0-counts.
A = [0 0 1 1 1 1 0 0 0 -1 -1 -1 0 1 1 0 ];
changeIdx = [1,diff(A)]~=0;
counts = histcounts(cumsum(changeIdx),1:sum(changeIdx)+1);
consecutiveCounts = [A(changeIdx)',counts']
% Result:
consecutiveCounts =
0 2 %First there are 2 zeros
1 4 %then 4 ones
0 3 %then 3 zeros
-1 3 %then 3 negative ones
0 1 % etc...
1 2
0 1
To get the vector you described, eliminate the 0-counts and multiply by the sign of the value in A so counts of negative numbers are negative.
consecutiveCounts(consecutiveCounts(:,1)~=0,2)' .* sign(consecutiveCounts(consecutiveCounts(:,1)~=0,1))'
ans =
4 -3 2
2 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!