MATLAB:快速转换一个布尔值。

时间:2023-01-18 21:21:55

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);

3 个解决方案

#1


16  

You could do the following:

你可以这样做:

x = ~x;

#2


6  

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

你可以用否定命题。我不记得它在matlab中是如何工作的,但我认为是这样的。

x = ~x;

#3


6  

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...

Franck的答案更好(用~),但我只是想指出,你的条件有点多余。很容易忘记,因为您已经有了一个布尔值,所以您不需要对条件进行比较。所以你可以这样做…

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

#1


16  

You could do the following:

你可以这样做:

x = ~x;

#2


6  

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

你可以用否定命题。我不记得它在matlab中是如何工作的,但我认为是这样的。

x = ~x;

#3


6  

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...

Franck的答案更好(用~),但我只是想指出,你的条件有点多余。很容易忘记,因为您已经有了一个布尔值,所以您不需要对条件进行比较。所以你可以这样做…

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