How to count the number of 1 between two 0 in a vector?

조회 수: 3 (최근 30일)
Nicolò Castellani
Nicolò Castellani 2020년 2월 3일
편집: Adam Danz 2021년 1월 17일
I have this vector:
[0 1 1 1 0 0 1 0 1 1 0 1]
I want to create a vector that every time that I have 1 or more consecutive 1 it counts the number of 1 between two zero. So the results must be:
[3 1 2 1]
How can I do that?
thanks

채택된 답변

Adam Danz
Adam Danz 2020년 2월 3일
편집: Adam Danz 2021년 1월 17일
In both methods below,
A is the input vector (row or column)
B is the output vector of consecutive 1 counts, row vector.
Method 1 assumes the vector only contains 1s and 0s
A = [0 1 1 1 0 0 1 0 1 1 0 1];
B = diff(find([0,A(:).',0]==0))-1;
B(B==0) = []
B = 1×4
3 1 2 1
Method 2 counts consecutive 1s, other elements can take any numeric value.
A = [0 1 1 1 0 0 1 0 1 1 0 1];
dA = diff([0,A(:).',0]==1);
B = find(dA==-1)-find(dA==1)
B = 1×4
3 1 2 1

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2020년 2월 3일
[regionprops(bwlabel([0 1 1 1 0 0 1 0 1 1 0 1]),'Area').Area]
  댓글 수: 3
Sean de Wolski
Sean de Wolski 2020년 2월 4일
A vector is just a long and skinny image! I find things like bwlabel, bwareaopen, etc. to often be useful for this kind of thing.
Adam Danz
Adam Danz 2020년 2월 4일
Agreed - I'm relatively new to the bw.... functions but I use bwlabel often. Since it requires access to a toolbox I went with a lower level solution in my answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Other Formats에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by