Longest Sequence of 1s
Afficher commentaires plus anciens
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 commentaire
John BG
le 27 Avr 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
Réponses (4)
Azzi Abdelmalek
le 27 Avr 2016
Modifié(e) : Azzi Abdelmalek
le 27 Avr 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 commentaire
Daniel
le 1 Oct 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
le 27 Avr 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
le 1 Oct 2018
Modifié(e) : Sean de Wolski
le 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'
Catégories
En savoir plus sur Data Type Identification dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!