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

22 visualizzazioni (ultimi 30 giorni)
Jaya il 24 Ott 2021
Commentato: Andreia Gomes il 15 Set 2022
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?
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Risposta accettata

Stephen23 il 24 Ott 2021
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 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Andreia Gomes il 15 Set 2022
Hello!
How can I do the same, but using a matrix with several rows and columns?
Thank you!

Accedi per commentare.

Più risposte (1)

Matt J il 24 Ott 2021
Modificato: Matt J il 24 Ott 2021
1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Jaya il 24 Ott 2021
This works perfectly fine too. But I accepted the other answer as that code is smaller and I used it.

Accedi per commentare.

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by