Skip to main content
Contents
Calc
Dark Mode Prev Next Profile
\(\newcommand\DLGray{\color{Gray}}
\newcommand\DLO{\color{BurntOrange}}
\newcommand\DLRa{\color{WildStrawberry}}
\newcommand\DLGa{\color{Green}}
\newcommand\DLGb{\color{PineGreen}}
\newcommand\DLBa{\color{RoyalBlue}}
\newcommand\DLBb{\color{Cerulean}}
\newcommand\ds{\displaystyle}
\newcommand\ddx{\frac{d}{dx}}
\newcommand\os{\overset}
\newcommand\us{\underset}
\newcommand\ob{\overbrace}
\newcommand\obt{\overbracket}
\newcommand\ub{\underbrace}
\newcommand\ubt{\underbracket}
\newcommand\ul{\underline}
\newcommand\tikznode[3][]
{\tikz[remember picture,baseline=(#2.base)]
\node[minimum size=0pt,inner sep=0pt,#1](#2){#3};
}
\newcommand\del{\nabla}
\newcommand\R{\mathbb{R}}
\newcommand\C{\mathcal{C}}
\newcommand\N{\mathcal{N}}
\newcommand\eps{\varepsilon}
\renewcommand\epsilon{\varepsilon}
\renewcommand\subset{\subseteq}
\newcommand\norm[1]{\|{#1}\|}
\newcommand\matrixbrackets[4][1]{
\draw (#3,#2) -- (\fpeval{#3+0.2},#2);
\draw (#3,#1) -- (#3 ,#2);
\draw (#3,#1) -- (\fpeval{#3+0.2},#1);
\draw (#4,#2) -- (\fpeval{#4-0.2},#2);
\draw (#4,#1) -- (#4 ,#2);
\draw (#4,#1) -- (\fpeval{#4-0.2},#1);
}
\tikzstyle{circle node 0}=[fill=white, draw=black, shape=circle, inner sep=0pt]
\tikzstyle{circle node 2}=[fill=white, draw=black, shape=circle, inner sep=2pt]
\tikzstyle{hrect node}=[fill=white, draw=black, inner sep=2pt, outer sep=3pt]
\tikzstyle{vrect node}=[fill=white, draw=black, inner sep=0pt, outer sep=0pt]
\tikzstyle{hidden node 0}=[inner sep=0pt, outer sep=0pt]
\tikzstyle{hidden node 2}=[fill=white, inner sep=2pt, outer sep=2pt]
\tikzstyle{rect node 1}=[fill=white, inner sep=2pt, outer sep=0pt]
\tikzstyle{rect node 2}=[fill=white, draw=black, inner sep=2pt, outer sep=0pt]
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Subsection If Statements
If Statement.
The simplest
if-statement tests a single logical condition. MATLAB evaluates the condition; if it is
true, the indented block runs. If it is
false, MATLAB skips the block and continues after
end.
The if Statement Structure.
if
condition is true, run
codeBlock.
if condition % true? β run codeBlock
codeBlock
end
Notes & Rules:
Every if-statement must end with end.
condition must be a logical statement that returns true or false.
If condition is false, MATLAB does nothing and skips to end.
To see how this works, run the following code block:
Since
age is
23, the logical statement
age >= 21 is true, so MATLAB executes the
fprintf line and prints the message. Now try changing
age to
16 and running it again. This time, the
age >= 21 is false, so MATLAB skips the
fprintf line and nothing is printed.
Checkpoint 27 .
(a) What happens when the condition is false?
In a basic
if statement, what happens when the condition is false?
MATLAB runs the block once and then stops the script.
The if statement never stops execution by itself.
MATLAB skips the block and continues with the line after end.
When the condition is false, MATLAB simply moves past the block.
MATLAB runs both the block and the next line after end.
Only one path executes: either the block runs or it is skipped.
MATLAB reports an error because the condition is false.
False conditions are expected, so no error is raised.
(b) Required keyword to close an if statement.
What keyword must appear at the end of every
if statement?
stop
MATLAB does not use stop to close an if statement.
end
Every if statement must be closed with end.
endif
MATLAB uses end instead of endif.
done
MATLAB does not use done to close an if statement.
(c) If statement requires true or false condition.
The condition in an
if statement must evaluate to either
true or
false.
True.
A logical condition is a statement that MATLAB evaluates to either true or false, which determines whether the code block executes.
False.
A logical condition is a statement that MATLAB evaluates to either true or false, which determines whether the code block executes.
If-else Statement.
When there are two mutually exclusive options, add an
else branch. MATLAB checks the
if condition once; if it is true, it executes the
if branch, and if it is false, it runs the
else branch. Exactly one branch runs each time the code executes.
The if-else Statement Structure.
if
conditionA is true, run
blockA. Otherwise, run
blockB.
if conditionA % true? β run blockA -- false? β run blockB
blockA
else
blockB
end
Notes & Rules:
Every if-statement must end with end.
conditionA must be a logical statement that returns true or false.
Exactly one of blockA OR blockB must run when the code executes.
Building on the previous example, here is a code block that uses an
if-else statement:
Since
age is
23, the logical statement
age >= 21 is true, so MATLAB prints the first message. Now try changing
age to
16 and running it again. This time, the logical statement is false, so MATLAB tells you to move along.
Checkpoint 28 .
(a) If-else executes exactly one branch.
In an
if-else statement, MATLAB executes exactly one of the two branches.
True.
Because the condition is either true or false, MATLAB runs the matching branch and skips the other.
False.
Because the condition is either true or false, MATLAB runs the matching branch and skips the other.
(b) When does the else branch run?
When does the
else branch in an
if-else statement execute?
The else branch runs before the if branch.
MATLAB checks the if condition first, then decides which branch to run.
The else branch runs when the condition is false.
The else branch is the alternative path that executes when the condition evaluates to false.
The else branch runs after the if branch completes.
Only one branch runs; they never both execute in the same pass through the code.
The else branch never runs.
The else branch runs whenever the condition is false.
(c) If-else provides two mutually exclusive paths.
An
if-else statement is useful when you need to choose between two mutually exclusive actions.
True.
The if-else structure guarantees that exactly one of two code paths executes based on whether the condition is true or false.
False.
The if-else structure guarantees that exactly one of two code paths executes based on whether the condition is true or false.
If-elseif-else Statement.
Use
elseif when you need to test several conditions in order. MATLAB checks each condition from top to bottom and executes the first block whose condition is true. An optional
else branch acts as a fallback so you can guarantee that a variable gets assigned a value.
The if-elseif-else Statement Structure.
if conditionA is true, run blockA,
if conditionB is true, run blockB,
if conditionC is true, run blockC,
if all of the above are false, run blockD (default).
if conditionA % true? β run blockA -- false? β check conditionB
blockA
elseif conditionB % true? β run blockB -- false? β check conditionC
blockB
elseif conditionC % true? β run blockC -- false? β run blockD
blockC
else
blockD
end
Notes & Rules:
You can add as many elseif branches as needed.
The else (default) branch is optional.
The conditions are checked in order from top to bottom.
Exactly one of the blocks will run when the code executes.
Every if-statement must end with end.
Each logicalStatement must evaluate to true or false.
The else block runs only when all preceding conditions are false.
You can nest if-statements within other if-statements, but this should be avoided whenever possible.
For practice, test this block with different initial values such as
x = 0; y = 4;,
x = 0; y = 3;, and
x = 3; y = 3;. Watch how only one branch executes each time.
Checkpoint 29 .
(a) How elseif chains work.
Which statements about an
if-elseif-else chain are true? Select all that apply.
Conditions are checked from top to bottom.
MATLAB evaluates conditions in order and stops at the first true one.
The else block runs even if a previous condition is true.
The else block is a fallback and only runs when all conditions are false.
Only the first true conditionβs block executes.
Once MATLAB finds a true condition, it skips the remaining branches.
You must include an else branch in every chain.
The else branch is optional, though it can be helpful as a default.
You can include multiple elseif branches.
Add as many elseif tests as you need to cover different cases.
(b) Order matters in elseif chains.
In an
if-elseif-else chain, changing the order of conditions can change which block executes.
True.
Because MATLAB checks conditions from top to bottom and stops at the first true one, the order of conditions matters. If multiple conditions could be true, only the first true conditionβs block will execute.
False.
Because MATLAB checks conditions from top to bottom and stops at the first true one, the order of conditions matters. If multiple conditions could be true, only the first true conditionβs block will execute.
(c) Purpose of the else branch.
What is the purpose of the
else branch in an
if-elseif-else chain?
To check one more condition before ending.
The else branch does not check a condition; use elseif to check additional conditions.
To provide a default action when no conditions are true.
The else branch serves as a fallback that runs when all previous conditions evaluate to false.
To close the if statement.
The end keyword closes the if statement, not else.
To run code after all other branches have executed.
Only one branch executes; the else runs instead of the others, not after them.
Exercises Review Questions
1.
(a) If Statement Requirements.
Every
if statement in MATLAB must end with the keyword
end.
True.
Correct! The end keyword is required to close every if statement, whether it contains just an if block, an if-else, or an if-elseif-else chain.
False.
Correct! The end keyword is required to close every if statement, whether it contains just an if block, an if-else, or an if-elseif-else chain.
(b) Else Branch Requirement.
An
else branch is required in every
if statement.
True.
Incorrect. The else branch is optional. If you only need to run code when a condition is true, you can use just an if block without an else.
False.
Incorrect. The else branch is optional. If you only need to run code when a condition is true, you can use just an if block without an else.
(c) Elseif Chain Evaluation Order.
In an
if-elseif-else chain, how does MATLAB determine which block to execute?
MATLAB checks all conditions and runs the block with the highest priority.
Incorrect. MATLAB evaluates conditions in order from top to bottom and stops at the first true condition.
MATLAB checks conditions from top to bottom and runs the first true block.
Correct! Once MATLAB finds a true condition, it executes that block and skips all remaining branches.
MATLAB checks all conditions and runs all blocks whose conditions are true.
Incorrect. Only one block executes in an if-elseif-else chain, even if multiple conditions are true.
MATLAB evaluates conditions randomly.
Incorrect. Conditions are always evaluated in the order they appear in the code.
(d) How Many Blocks Execute?
x = 10;
if x > 5
y = 1;
elseif x > 8
y = 2;
elseif x > 3
y = 3;
else
y = 0;
end
What is the value of
y after this code executes?
y = 2
Incorrect. The first condition (x > 5) is true, so MATLAB never checks the second condition.
y = 3
Incorrect. The first condition (x > 5) is true, so MATLAB never checks the third condition.
y = 6 (sum of 1+2+3)
Incorrect. Only one block executes in an if-elseif-else chain. The blocks donβt accumulate.
y = 1
Correct! Even though x > 8 and x > 3 are also true, MATLAB stops at the first true condition (x > 5) and assigns y = 1.
(e) Nested If vs Elseif Chain.
What is the main difference between using nested
if statements and using an
if-elseif chain?
There is no difference; they are equivalent in all cases.
Incorrect. Nested if statements can check multiple conditions independently, while elseif chains are mutually exclusive.
Nested if statements run faster than elseif chains.
Incorrect. Performance is not the key difference; the distinction is in the logic structure and whether branches are mutually exclusive.
Nested if statements can allow multiple blocks to execute; elseif chains execute only one block.
Correct! In an if-elseif-else chain, only one block runs. With nested if statements, multiple independent conditions can be true.
Elseif chains require more end keywords than nested if statements.
Incorrect. Actually, nested if statements require more end keywords (one for each if), while an elseif chain needs only one.
(f) If Statement Condition Type.
x = 5;
if x
disp('x is true')
else
disp('x is false')
end
What will be displayed, and why?
x is true, because any non-zero number is treated as true.
Correct! In MATLAB, non-zero values are treated as true in conditional statements, and zero is treated as false.
x is false, because x is not a logical value.
Incorrect. While x is numeric, MATLAB automatically converts non-zero numbers to true in conditional statements.
An error occurs because x is not a logical value.
Incorrect. MATLAB allows numeric values in if conditions and treats non-zero as true and zero as false.
x is false, because 5 is not equal to true.
Incorrect. MATLAB doesnβt compare x to true; it converts non-zero values to true.