MATLAB: quick access to boolean value

Is there a faster way than the following: to "turn" the truth or falsehood into its opposite state?

if x == true x = false; else x = true; end 

Yes, maybe just five lines of code have nothing to worry about, but something more like this would be fantastic:

 x = flip(x); 
+7
source share
3 answers

You can do the following:

 x = ~x; 
+16
source

u can use the negation operator. I can’t remember how it works in Matlab, but I think it’s something like

 x = ~x; 
+6
source

Franck's answer is better (using ~), but I just wanted to point out that the conditional in yours is a bit redundant. It’s easy to forget that since you already have a boolean, you don’t need to do a conditional comparison. So you could just do it ...

 if x x = false; else x = true; end 
+6
source

All Articles