Graphics Programs Reference
In-Depth Information
Logical Expressions
In the examples above, we used relational operator s suchas >= , > , and ==
to form a logical expression, and we instructed MATLAB to choose between
different commands according to whether the expression is true or false. Type
help relop to see all of the available relational operators. Some of these
operators, suchas & (AND) and | (OR), can be used to form logical expressions
that are more complicated than those that simply compare two numbers. For
example, the expression (x>0)| (y>0) will be true if x or y (or both)
is positive, and false if neither is positive. In this particular example, the
parentheses are not necessary, but generally compound logical expressions
like this are both easier to read and less prone to errors if parentheses are
used to avoid ambiguities.
Thusfarinourdiscussionofbranching,wehaveonlyconsideredexpressions
that can be evaluated as true or false. While such expressions are sufficient
for many purposes, you can also follow if or elseif withany expression
that MATLAB can evaluate numerically. In fact, MATLAB makes almost no
distinction between logical expressions and ordinary numerical expressions.
Consider what happens if you type a logical expression by itself in the Com-
mand Window:
>>2>3
ans =
0
When evaluating a logical expression, MATLAB assigns it a value of 0 (for
FALSE) or 1 (for TRUE). Thus if you type 2<3 , the answer is 1 . The rela-
tional operators are treated by MATLAB like arithmetic operators, inasmuch
as their output is numeric.
MATLAB makes a subtle distinction between the output of relational
operators and ordinary numbers. For example, if you type whos after the
command above, you will see that ans is a logical array . We will give an
example of how this feature can be used shortly. Type help logical for
more information.
Here is another example:
>>2|3
ans =
1
Search WWH ::




Custom Search