开发者

Matlab: binary numbers when used as booleans don't behave as expected?

I'm trying to use the components of binary numbers as booleans in Matlab. Unfortunately they don't behave as I would expect them to. Take for example the following code:

for x = dec2bin(0:1)'
    x(1)  % the leading bit of x
    if logical(x(1))
        disp('yes')
    else
        disp('no')
   开发者_运维技巧 end
end

It outputs:

ans = 0
yes
ans = 1
yes

Does anybody know why that is, and how I can get it to output 'yes' when x(1) is 1, and 'no' otherwise?

Thanks!


dec2bin() converts a number to a string representation, so x(1) obtains a char, not an int. Therefore, it will be the ASCII value corresponding to '0' or '1' (48 or 49, respectively). logical() simply tests whether its argument is non-zero, which is true in both cases.

The solution is simply to use bitget() instead.


IIRC the output of dec2bin is a string, not a number. So you are not getting 0 or 1, but rather '0' or '1'

Try

if( strncmp(x(1),'1',1) )

instead


In this case bitget indeed appears to be the most practical solution as pointed out by @Oli , however a general alternative to change a string into the corresponding array of values is substracting the character value of zero.

for x = dec2bin(0:1)'
    x(1)  % the leading bit of x
    if x(1) - '0' 
        disp('yes')
    else
        disp('no')
    end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜