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 comentario

John BG
John BG el 27 de Abr. de 2016
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

Iniciar sesión para comentar.

Respuestas (4)

Azzi Abdelmalek
Azzi Abdelmalek el 27 de Abr. de 2016
Editada: Azzi Abdelmalek el 27 de Abr. de 2016

1 voto

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 comentario

Daniel
Daniel el 1 de Oct. de 2018
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 :)

Iniciar sesión para comentar.

Image Analyst
Image Analyst el 27 de Abr. de 2016

0 votos

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 el 1 de Oct. de 2018
Editada: jonas el 1 de Oct. de 2018

0 votos

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 el 1 de Oct. de 2018
Editada: Sean de Wolski el 1 de Oct. de 2018

0 votos

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'

Categorías

Más información sobre Data Type Identification en Centro de ayuda y File Exchange.

Preguntada:

el 27 de Abr. de 2016

Editada:

el 1 de Oct. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by