Skip to main content

Section 12.2 True and False

We saw above that the relational operations evaluate to either True or False. In computer science True and False are referred to as booleans. That isn’t super important to remember for now. Instead, the important thing to learn is that, unlike other programming languages, MATLAB is extremely flexible and allows both True and False to be represented in a number of ways.
In MATLAB, the keyword true can be used or the number 1 can be used to represent True. Similarly, the keyword false and the number 0 can be used to represent False.
Try It!
The best way to understand what I am trying to say is to try it yourself. So fire up MATLAB and let’s investigate how the relational operators work. The brain workout part of this is that you should stop and think about what should happen before you run any of the following commands! It will be impossible for anyone to know if you skip this step or not but do not skimp on your brain workouts!
To begin, let’s define a few variables in the workspace to work with (we will use them in other examples so it is a good idea to keep them around):
tomato=23;
cucumber=-12;
salmon=7*8;
Next, we can use those variables to investigate how the relational operators work. For example, try executing the following operation in the command window. Before you hit enter, what do you think should happen?

Example 12.2.1. Logical Example.

Here is an interactive code box that functions identically to the MATLAB command window.
Hopefully, you aren’t jumping ahead and are actually taking a moment to think. In any case, you should notice that MATLAB assigns the automatic variable ans the value of 1 which is to say that the operation is evaluated as true. That makes sense since tomato is a variable storing the number 23 and cucumber is storing -12, it is clear that \(23>-12\) and we would expect MATLAB to think this is true.
We can also assign the output of a relational operation to a variable. To see this in action try:
result_1=salmon<tomato
Notice that MATLAB creates a new variable in the workspace called result_1 and that it is storing the number 0 which is the same thing as false. That is what we would have expected the following operation to evaluate to.

Checkpoint 12.2.2. Output for Relational Operators.

You have attempted of activities on this page.