Clear Filters
Clear Filters

What is wrong with the code?

2 views (last 30 days)
GEORGIOS BEKAS
GEORGIOS BEKAS on 23 Jan 2018
Commented: GEORGIOS BEKAS on 24 Jan 2018
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 Comments
Walter Roberson
Walter Roberson on 23 Jan 2018
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)

Sign in to comment.

Accepted Answer

Birdman
Birdman on 24 Jan 2018
Use regexp.
regexp(s,'1*','match')
and you will find that the longest subsequence consists of 4 elements.
  1 Comment
GEORGIOS BEKAS
GEORGIOS BEKAS on 24 Jan 2018
if isempty(y) == 1 y = 0 else y=length(y{max(length(y))} ) end

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 24 Jan 2018
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 Comments
Walter Roberson
Walter Roberson on 24 Jan 2018
What did you change your code to?

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!