Skip to main content
Logo image

Subsection Joining Two Statements

Many questions involve multiple conditions. For example, to determine if a number is an even number greater than 100, then you need to check two things at once:
Because both must be true, we join these statements with β€œand”. If either of these conditions could be true, then we would join them with β€œor”.
MATLAB joins logical statements with AND and OR using the operators & (AND) and | (OR).
Table 23. Logical operators for combining statements
\(\textbf{Logical}\) \(\textbf{operator}\)
\(\textbf{Logical statement}\)
\(\textbf{Question being asked}\)
&
ans1 & ans2
Are both \(\texttt{ans1}\) and \(\texttt{ans2}\) true?
| ans1 | ans2 \(\text{Is at least one of}\ \texttt{ans1}\ \text{or}\ \texttt{ans2}\ \text{true?}\)
The result of joining logical statements are exactly what you would expect from everyday language: AND is true only when both sides are true, while OR is true when at least one side is true.
% Quick checks
true  & true	% β†’ true:  1 (logical)
true  & false	% β†’ false: 0 (logical)
false & true	% β†’ false: 0 (logical)
false & false	% β†’ false: 0 (logical)

true  | true	% β†’ true:  1 (logical)
true  | false	% β†’ true:  1 (logical)
false | true	% β†’ true:  1 (logical)
false | false	% β†’ false: 0 (logical)
Now try these operators in context.
P = 1;
Q = 10;
R = -4;

P <= R & P > Q	  % β†’ false	& false: 0 (logical)
R < 0 & R < Q	  % β†’ true	& true:  1 (logical)
Q == R | Q == P	  % β†’ false	| false: 0 (logical)
P < Q | P < R	  % β†’ true	| false: 1 (logical)

~(P < Q & P < R)  % β†’ NOT (true & false): 1 (logical)
P > Q | P > R	  % β†’ false | true:		  1 (logical)

Checkpoint 24. Combining Logical Statements.

Given age = 25 and hasLicense = true, which expression is the most readable way to ask "Is the person at least 18 years old AND has a driver’s license?"
  • (age >= 18) & hasLicense
  • Correct! This is clear and readable, using the AND operator directly with meaningful variable names.
  • (age >= 18) | hasLicense
  • Incorrect. The OR operator returns true if either condition is true, but we need both conditions to be true.
  • age >= 18 & hasLicense == true
  • While logically correct, comparing hasLicense == true is redundant and less readable. Use hasLicense directly since it’s already a logical value.
  • ~(age < 18 | ~hasLicense)
  • While logically equivalent (using De Morgan’s Law), this is much harder to read. Prefer the straightforward AND version for clarity.