What is wrong with the code?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
GEORGIOS BEKAS
el 23 de En. de 2018
Comentada: GEORGIOS BEKAS
el 24 de En. de 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 comentarios
Walter Roberson
el 23 de En. de 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)
Respuesta aceptada
Birdman
el 24 de En. de 2018
Use regexp.
regexp(s,'1*','match')
and you will find that the longest subsequence consists of 4 elements.
Más respuestas (1)
Walter Roberson
el 24 de En. de 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 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!