How to find the longest time an array has a zero value in a row

2 views (last 30 days)
I have a 1x1441 array consisting of only 1s and 0s, such as [0 0 1 1 1 0 0 0 1 1 1]. I need to find the longest amount of consecutive 0s in the array and have it be returned. In this case there are two sets of consecutive 0s, [0 0] and [0 0 0], so the returned value would need to be 3.

Accepted Answer

Image Analyst
Image Analyst on 4 Jul 2017
You said "find" but then I guess you want the length, not the location. So to find the longest length of zeros, if you have the Image Processing Toolbox, you can do it in one line of code:
vec = [0 0 1 1 1 0 0 0 1 1 1] % Create sample data.
longestZeroLength = sum(bwareafilt(vec==0, 1)) % returns 3.

More Answers (1)

KSSV
KSSV on 4 Jul 2017
A = [0 0 1 1 1 0 0 0 1 1 1] ;
idx = find(A==0) ; % get the indices of 0
a=diff(idx); % get the differences of indices
b=find([a inf]>1);
c=diff([0 b]); % length of the sequences
d=cumsum(c); % endpoints of the sequences
% Run loop to extract zeros into iwant
iwant = cell(length(d),1) ;
iwant{1} = A(1:idx(d(1))) ;
for i = 2:length(d)
iwant{i} = A(idx(d(i-1)+1:d(i))) ;
end

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!