Finding sequences of consecutive 1s

12 views (last 30 days)
Brian Dunphy
Brian Dunphy on 27 Apr 2016
Commented: EFB on 4 Mar 2019
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?

Answers (3)

Roger Stafford
Roger Stafford on 27 Apr 2016
Edited: Roger Stafford on 27 Apr 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 on 27 Apr 2016
hint: strfind(AVector, [0 1]) tells you something about when you have a 0 followed by a 1

Jan
Jan on 27 Apr 2016
Edited: Jan on 27 Apr 2016
With FEX: RunLength without a conversion to numbers:
[b, n] = RunLength(n);
output = max(n(b == '1'));

Categories

Find more on Characters and Strings 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!