des4maisons
des4maisons

Reputation: 1881

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!

Upvotes: 1

Views: 926

Answers (3)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21561

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

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272717

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.

Upvotes: 6

KitsuneYMG
KitsuneYMG

Reputation: 12901

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

Upvotes: 4

Related Questions