Counting consecutive occurences of 1s and -1s

4 ビュー (過去 30 日間)
Mohammad Zulqarnain
Mohammad Zulqarnain 2019 年 5 月 1 日
コメント済み: Adam Danz 2019 年 5 月 2 日
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

採用された回答

Adam Danz
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 件のコメント
Mohammad Zulqarnain
Mohammad Zulqarnain 2019 年 5 月 2 日
Thank you Adam Danz !!!
Adam Danz
Adam Danz 2019 年 5 月 2 日
That was a fun one! I think I'll use it myself some time.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by