필터 지우기
필터 지우기

What is wrong with the code?

조회 수: 2 (최근 30일)
GEORGIOS BEKAS
GEORGIOS BEKAS 2018년 1월 23일
댓글: GEORGIOS BEKAS 2018년 1월 24일
I am trying to find the logest subsequence of 1s in a string. I am doing something wrong.
s='0101010111000101110001011100010100001110110100000000110001001000001110001000111010101001101100001111'
c=[]
counter = 0
for i = 2:length(s)
while str2num(s(i)) == 1 && str2num(s(i)) == str2num(s(i-1))
counter = counter+1
c = [c,counter]
if str2num(s(i)) ==0
counter = 0
end
end
end
  댓글 수: 2
Walter Roberson
Walter Roberson 2018년 1월 23일
hint: instead of doing str2num() and comparing to 1, you can just compare s(i) == '1', and you can compare s(i) == s(i-1)
GEORGIOS BEKAS
GEORGIOS BEKAS 2018년 1월 23일
does not work

댓글을 달려면 로그인하십시오.

채택된 답변

Birdman
Birdman 2018년 1월 24일
Use regexp.
regexp(s,'1*','match')
and you will find that the longest subsequence consists of 4 elements.
  댓글 수: 1
GEORGIOS BEKAS
GEORGIOS BEKAS 2018년 1월 24일
if isempty(y) == 1 y = 0 else y=length(y{max(length(y))} ) end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 1월 24일
You have
counter = 0;
for i = 2:length(s)
while str2num(s(i)) == 1 && str2num(s(i)) == str2num(s(i-1))
counter = counter+1
c = [c,counter]
if str2num(s(i)) ==0
counter = 0
end
end
Trace it through.
Start with i = 2.
s(2) == 1 but s(1) is not 1, so end the while.
Go on to i = 3. s(3) == 0, so end the while.
Go on to i = 4. s(4) == 1, but s(3) is not 1, so end the while.
Go on to i = 5.... etc. You keep ending the while immediately until...
i = 9. s(9) == 1 and s(9) and s(8) are both 1, so enter the while loop.
Inside the while loop, increment counter to 1 and adjust c. s(9) is still not 0 so do not reset counter to 0. Continue around in the while loop.
i is still 9. s(9) and s(8) are still both 1, so enter the while loop. Inside the while loop, increment counter to 2 and adjust c. s(9) is still not 0, so do not reset counter to 0. Continue in the while loop.
i is still 9. s(9) and s(8) are still both 1, so enter the while loop. Inside the while loop, increment counter to 3 and adjust c. s(9) is still not 0, so do not reset counter to 0. Continue in the while loop.
...
ummm... when do we end the while loop? The while loop tests s(i) and s(i-1) but does not change either location and does not change i, so once entered, the while loop will never end.
  댓글 수: 2
GEORGIOS BEKAS
GEORGIOS BEKAS 2018년 1월 24일
does not work
Walter Roberson
Walter Roberson 2018년 1월 24일
What did you change your code to?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by