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

1 次查看(过去 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 个评论

请先登录,再进行评论。

采纳的回答

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 中查找有关 Axis Labels 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by