Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Inverting a boolean value quickly

Tags:

boolean

matlab

Is there a quicker way than the following to 'flip' a true or false to its opposite state?

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

Yes, perhaps only five lines of code is nothing to worry about but something that looks more like this would be fantastic:

x = flip(x);
like image 652
CaptainProg Avatar asked Feb 02 '12 16:02

CaptainProg


3 Answers

You could do the following:

x = ~x;
like image 189
Franck Dernoncourt Avatar answered Oct 27 '22 02:10

Franck Dernoncourt


u can use negation statement. I cant remember how it works in matlab, but i think is something like

x = ~x;
like image 22
groovekiller Avatar answered Oct 27 '22 03:10

groovekiller


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

if x
  x = false;
else
  x = true;
end
like image 36
Bob Gilmore Avatar answered Oct 27 '22 01:10

Bob Gilmore