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?
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
                        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))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With