Asked by Jon Mick
on 13 Sep 2019

I have a double that is 5644x1 and it consists of nothing but 0's and 1's.

ex: 00000000101100000011110000110000

I want to count the longest length of repeated 0's in this double, which in the case of this example would be 8. Can you please help?

Answer by John D'Errico
on 13 Sep 2019

Edited by John D'Errico
on 13 Sep 2019

First, this is NOT a double vector.

00000000101100000011110000110000

It might be a string. But if you tried to write that vector as a double, it would be just one number, in decimal form. So you might have it stored as a vector binary elements. I'll assume you have a character string, but the answer is trivially changed if not.

V = '00000000101100000011110000110000';

We are looking for the longest length of repeated 0's.

st10 = strfind(['1',V],'10') + 1;

st01 = strfind([V,'1'],'01');

st01 - st10 + 2

ans =

8 1 6 4 4

So the length of the LONGEST such string of zeros is just...

max(st01 - st10 + 2)

ans =

8

If your vector is actually a numeric vector, perhaps like this, strfind still works

V=[0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0];

st10 = strfind([1,V],[1 0]) + 1;

st01 = strfind([V,1],[0 1]);

max(st01 - st10 + 2)

ans =

8

Adam Danz
on 14 Sep 2019

I didn't know strfind() does that, too. Nice!

John D'Errico
on 14 Sep 2019

I guess it is one of those features that date back to the dark ages of MATLAB, when there was sort of a duality beween strings and numeric integer vectors containing ASCII code values. The reason why you can still do things like this:

C = 'ABCDE';

+C % ascii code values

ans =

65 66 67 68 69

C - 'A'

ans =

0 1 2 3 4

N = '012345';

N - '0'

ans =

0 1 2 3 4 5

Adam Danz
on 14 Sep 2019

char([73 39 108 108 32 104 97 118 101 32 102 117 110 32 119 105 116 104 32 116 104 105 115 33])

Sign in to comment.

Answer by Image Analyst
on 13 Sep 2019

You can use regionprops(), if you have the Image Processing Toolbox

signal = [0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0];

props = regionprops(logical(signal == 0), 'Area'); % Measure lengths of each run of zeros

longestStretch = max([props.Area]) % Find the length of the longest one.

You get:

longestStretch =

8

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.