problem with if statment

12 views (last 30 days)
huda nawaf
huda nawaf on 20 Aug 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

Answers (2)

Arturo Moncada-Torres
Arturo Moncada-Torres on 20 Aug 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 on 20 Aug 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.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!