Counting consecutive occurences of 1s and -1s

4 vues (au cours des 30 derniers jours)
Mohammad Zulqarnain
Mohammad Zulqarnain le 1 Mai 2019
Commenté : Adam Danz le 2 Mai 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

Réponse acceptée

Adam Danz
Adam Danz le 2 Mai 2019
Modifié(e) : Adam Danz le 2 Mai 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 commentaires
Mohammad Zulqarnain
Mohammad Zulqarnain le 2 Mai 2019
Thank you Adam Danz !!!
Adam Danz
Adam Danz le 2 Mai 2019
That was a fun one! I think I'll use it myself some time.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by