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 Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by