Counting consecutive occurences of 1s and -1s

조회 수: 3 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by