Counting consecutive occurences of 1s and -1s
2 views (last 30 days)
Show older comments
Mohammad Zulqarnain
on 1 May 2019
Commented: Adam Danz
on 2 May 2019
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 Comments
Accepted Answer
Adam Danz
on 2 May 2019
Edited: Adam Danz
on 2 May 2019
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 Comments
More Answers (0)
See Also
Categories
Find more on Logical 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!