Borrar filtros
Borrar filtros

problem with if statment

2 visualizaciones (últimos 30 días)
huda nawaf
huda nawaf el 20 de Ag. de 2011
hi,
I write very simple code
x=dec2bin(1024);
for i=1:11
if x(i)== 0
i
end
end
when I ran it , I don't know why it not meet the condition , then print i.
this code is part from a long code that relate my work.
thanks

Respuestas (2)

Arturo Moncada-Torres
Arturo Moncada-Torres el 20 de Ag. de 2011
The problem is that dec2bin returns the binary number in a string and not in a numeric format. You can try any of these two options. I already tested them and work perfectly:
Option 1
x=dec2bin(1024);
for i=1:11
if strcmp(x(i), '0')
i
end
end
Option 2
x=dec2bin(1024);
for i=1:11
if str2double(x(i)) == 0
i
end
end

David Young
David Young el 20 de Ag. de 2011
It's because the result from dec2bin is a character string. So each element of the array x represents a character, '0' or '1', from the binary representation of 1024. If you replace
if x(i) == 0
with
if x(i) == '0'
you will find you get the behaviour you expect (that is, it prints i=2, i=3 etc.)
The character '0' is usually represented by the numerical value 48, which of course is not equal to zero, so nothing is printed in your original code.
  1 comentario
Arturo Moncada-Torres
Arturo Moncada-Torres el 20 de Ag. de 2011
Yeah, that one would work too :P

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by