Longest Sequence of 1s
Mostrar comentarios más antiguos
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
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
Respuestas (4)
Azzi Abdelmalek
el 27 de Abr. de 2016
Editada: Azzi Abdelmalek
el 27 de Abr. de 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 comentario
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 :)
Image Analyst
el 27 de Abr. de 2016
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.
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
el 1 de Oct. de 2018
Editada: Sean de Wolski
el 1 de Oct. de 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'
Categorías
Más información sobre Data Type Identification en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!