What are Bools?
Boolean variables, or bools, are logical values. For example, this could be true and false, 1 and 0, etc. Boolean variables allow us to use conditional logic in order to more precisely execute the code or paths we would like. In MATLAB, true and false are actually predefined as 1 and 0, respectively, so either would work for when working with conditionals.
Bool Logicals
There are several logical operators that are often used with boolean variables. Let's take a look at a few:
- & - the AND operator: this operator checks to see if both inputs are true. If they are, then the output is true.
- && - the AND operator with short circuiting: this operator first checks if the first value is false. If the first value is false, then it does not matter what the second value is because both need to be true in order for the output to be true. So, this "short circuiting" helps your script running faster because it saves time checking the second input if the first already fails.
- | - the OR operator: this operator checks to see if either input is true. If either input, or both inputs, are true, then the output is true.
- || - the OR operator with short circuiting: this operator checks the first input and determines if it true or not. If it is, it outputs true without looking at the second input because the OR operator only needs one input to be true in order to output true. The OR operator with short circuiting helps save time similar to the AND operator with short circuiting.
- ~ - the NOT operator: this operator takes the current logical value and flips its value. For example, if the current value is 1, then after using the NOT operator, the value will be 0, and vice versa.
- xor - the Exclusive OR operator: this operator checks to see if only one input is true to output a true. If both are true or both are false, then it will output a false.
- > - the greater than operator: this checks to see if a value is greater than the other.
- >= - the greater than or equal to operator: this checks to see if a value is greater than or equal to another.
- < - the less than operator: this operator checks to see if a value is less than the other.
- <= - the less than or equal to operator: this checks to see if a value is less than or equal to another.
- == - the equal to operator: this checks to see if a value is equal to another.
We will dive into boolean variables much more once we get to the conditional logic topic!