Vectorized method to find the number of consecutive 1s from the left of an array

조회 수: 3 (최근 30일)
Hi, I want to find the number of consecutive 1s from the left of an array (a binary array). For example, if I have A = [1 1 1 0 1 0 0 0 1 1] then the result would be 3 because there are 3 consecutive 1s from the left. Another example: A = [1 0 1 1 1 1 1] then the result would be 1. Or A = [0 1 1 1 0 0 1 0 1], the result would be 0.
I can write this in for loop, however I do not know how to vectorize this part. I really need it for my code so that it might run faster.
Please help me, thank you very much.
  댓글 수: 4
Dang Manh Truong
Dang Manh Truong 2019년 1월 27일
Hey, when I try A = [1 1 1 1 1 1] it gives me an error :(

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

채택된 답변

madhan ravi
madhan ravi 2019년 1월 27일
편집: madhan ravi 2019년 1월 27일
idx=find(diff(A));
if A(1)==0
Result=0
elseif all(A)
Result=numel(A)
else
Result=idx(1)
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by