Effacer les filtres
Effacer les filtres

problem with if statment

1 vue (au cours des 30 derniers jours)
huda nawaf
huda nawaf le 20 Août 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

Réponses (2)

Arturo Moncada-Torres
Arturo Moncada-Torres le 20 Août 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 le 20 Août 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 commentaire
Arturo Moncada-Torres
Arturo Moncada-Torres le 20 Août 2011
Yeah, that one would work too :P

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by