Longest Sequence of 1s

I have a code for finding the longest sequence of consecutive ones but I am having problems with certain inputs giving improper results.
% code
function output=longest_one(n)
b=['0' n '0']
ib=strfind(b,'01')
ie=strfind(b,'10')
il=ie-ib
output=max(il)
if max(n)==0
output=0
end
When n='1 1 1 1 0 0 0 0 1 1 1 1' is inputted I receive a value of 23 instead of 4.
n =
1 1 1 1 0 0 0 0 1 1 1 1
longest_ones(n) ans = 23

1 Comment

translate from characters with
nn=str2num(n)
you read 23 because your function counts figures and spaces equally, after all they are all characters.
And in 1st line of your function, do you really need to add head and tail zeros?
John

Sign in to comment.

Answers (4)

Azzi Abdelmalek
Azzi Abdelmalek on 27 Apr 2016
Edited: Azzi Abdelmalek on 27 Apr 2016
n=[1 1 1 1 0 0 0 1 1 1 1]
longest=max(accumarray(nonzeros((cumsum(~n)+1).*n),1))
If n is a string
n='1 1 1 1 0 0 0 0 1 1 1 1'
n=str2num(n)
longest=max(accumarray(nonzeros((cumsum(~n)+1).*n),1))
Or
out=max(cellfun(@numel,regexp(strrep(n,' ',''),'1+','match')))

1 Comment

Can you explain "max(accumarray(nonzeros((cumsum(~n)+1).*n),1))" this piece of code? What is the logic to combine all these operatins in such a way?
Thanks :)

Sign in to comment.

This is trivial if you have the Image Processing Toolbox
measurements = regionprops(logical(n), 'Area');
output = max([measurements.Area])
Where n is an array of 0's and 1's - not a string.
jonas
jonas on 1 Oct 2018
Edited: jonas on 1 Oct 2018
Here's another one
%%remove blanks
n= n(find(~isspace(n)));
%%save all trailing ones
out=regexp(n,'1+','match')
%%Find largest
max(cellfun(@numel,out))
edit: did not realize I was late to the party
Sean de Wolski
Sean de Wolski on 1 Oct 2018
Edited: Sean de Wolski on 1 Oct 2018
biggest = bwareafilt(x, 1)
If x is a char array, then convert it to a double using:
double(split(string(x)))
or
x = x(~isspace(x))-'0'

Categories

Asked:

on 27 Apr 2016

Edited:

on 1 Oct 2018

Community Treasure Hunt

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

Start Hunting!