Finding sequences of consecutive 1s

I need to make a function to find longest string of consecutive ones. I have code but it will record the longest string regardless of whether or not its a 1 or 0.
% code
function output=longest_one(n)
n=str2num(n);
size_n=size(n);
size_n=size_n(2);
lenmax = 1;
len = 1;
for i = 2:size_n
if n(i) == n(i-1)
len = len+1;
else
if len >= lenmax
lenmax = len;
end
len=1;
end
end output=lenmax end
Any ideas on how to just get the longest string of ones?

Réponses (3)

Roger Stafford
Roger Stafford le 27 Avr 2016
Modifié(e) : Roger Stafford le 27 Avr 2016
Assume 'n' is a row vector.
f = find(diff([false,n==1,false])~=0);
[m,ix] = max(f(2:2:end)-f(1:2:end-1));
The value of 'm' is the longest string's length, and it starts at f(2*ix-1) in 'n'.
Walter Roberson
Walter Roberson le 27 Avr 2016

0 votes

hint: strfind(AVector, [0 1]) tells you something about when you have a 0 followed by a 1
Jan
Jan le 27 Avr 2016
Modifié(e) : Jan le 27 Avr 2016
With FEX: RunLength without a conversion to numbers:
[b, n] = RunLength(n);
output = max(n(b == '1'));

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Commenté :

EFB
le 4 Mar 2019

Community Treasure Hunt

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

Start Hunting!

Translated by