フィルターのクリア

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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by