problem with if statment

조회 수: 2 (최근 30일)
huda nawaf
huda nawaf 2011년 8월 20일
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

답변 (2개)

Arturo Moncada-Torres
Arturo Moncada-Torres 2011년 8월 20일
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 2011년 8월 20일
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
Arturo Moncada-Torres
Arturo Moncada-Torres 2011년 8월 20일
Yeah, that one would work too :P

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by