Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable is boolean

Tags:

matlab

how to check if a variable is boolean in MATLAB?

I have a function

function myFunc(myBoolean)
  if myBoolean~=true && myBoolean~=false
  assert(false,'variable should be boolean);
end
x = test(myBoolean);

How to improve?, is there a function to check if a variable isn't true/false?

like image 984
lola Avatar asked Dec 04 '22 05:12

lola


2 Answers

Use the isa function. For your case (from the help file), you would use:

isa(true(2,3),'logical')
ans = 
      1

There is also the dedicated islogical function.

islogical(true(2,3))
ans = 
      1
like image 149
craigim Avatar answered Jan 06 '23 09:01

craigim


There is no "Boolean" type or class in Matlab. As @craigm has indicated, there is a logical class in which true and false reside. A problem that can occur, however, is something like this:

test = 1;
if test == true
    class(test)
end

Is test Boolean? As I'm sure you know, the if statement will evaluate to true and class(test) will return 'double', not 'logical'. This is a design choice on the part of The MathWorks and fits with most other programming languages: 0 and 1 from any type are commonly used for true and false. (uint8(1) == 1 also returns true – values, not the class, are compared.)

So, yes, if you know that your code actually is using logical values to represent Booleans (a good idea in many cases) then islogical is all you need (see here for even more examples). However, a more general (and vectorized) solution might be:

isBoolean = @(x)islogical(x) || isnumeric(x) && all(x(:)==0 | x(:)==1)

Then the following all return logical true:

isBoolean(true)
isBoolean(false)
isBoolean(zeros(1,3))
isBoolean(eye(3))
isBoolean(uint8(1))
like image 31
horchler Avatar answered Jan 06 '23 10:01

horchler