Finding consecutive zeros in an array. Not able to solve using diff command

조회 수: 29 (최근 30일)
I have an array like below
a=[0 0 1 1 -1 0 0 0 1 1 1 -1 0 0 1 -1] %in my actual code, there are many elements
There is a -1 after every set of 1s like an end marker. I want to find the largest number of consecutive zeros present. Here it would be 3.
I used diff(a) but in this case even 1-1=0 along with 0-0=0. I also tried manipulating the array with some math operations and then using diff(a) but no use.
Any idea on how to do this?

채택된 답변

Stephen23
Stephen23 2021년 10월 24일
a = [0,0,1,1,-1,0,0,0,1,1,1,-1,0,0,1,-1];
d = diff([false,a==0,false]);
b = find(d>0);
e = find(d<0);
m = max(e-b)
m = 3
  댓글 수: 1
Andreia Gomes
Andreia Gomes 2022년 9월 15일
Hello!
How can I do the same, but using a matrix with several rows and columns?
Thank you!

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

추가 답변 (1개)

Matt J
Matt J 2021년 10월 24일
편집: Matt J 2021년 10월 24일
  댓글 수: 1
Jaya
Jaya 2021년 10월 24일
This works perfectly fine too. But I accepted the other answer as that code is smaller and I used it.

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

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by