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
John BG
2016년 4월 27일
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
답변 (4개)
Azzi Abdelmalek
2016년 4월 27일
편집: Azzi Abdelmalek
2016년 4월 27일
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
Daniel
2018년 10월 1일
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
2016년 4월 27일
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
2018년 10월 1일
편집: Sean de Wolski
2018년 10월 1일
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'
카테고리
도움말 센터 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!