Conditionals
Whether or not a block of code is executed in MATLAB can be controlled using if statements.
Coupled with elseif and else, you can write code that is executed depending on whether a logical expression is true.
For example, water boils into steam if the temperature is greater than the boiling point.
The MATLAB Help Center has a guide on Conditional Statements.
Syntax
Conditional statements in MATLAB follow this general structure:
if condition1
statements1
elseif condition2
statements2
else
statements3
end
Each condition is evaluated in order.
If condition1 is true, statements1 are executed and the rest are skipped.
If condition1 is false but condition2 is true, statements2 are executed.
If none of the conditions are true, the else block is executed.
The elseif and else blocks are both optional.
Logical Expressions
Conditions are typically logical expressions involving relational operators (<, >, ==, ~=, etc.) or logical operators (&&, ||, ~).
MATLAB treats a condition as true if it is nonempty and all elements are nonzero.
x = 5;
if x > 0
disp('Positive')
elseif x == 0
disp('Zero')
else
disp('Negative')
end
Positive
Example: Material Selection
Question
An engineer is selecting a material for a structural component. The material must have a yield strength above 250 MPa and a density below 8000 kg/m3. Write a MATLAB script to check if a material with yield strength 300 MPa and density 7800 kg/m3 meets these criteria.
Solution
To evaluate the fitness of the material, we use if statements to check the criteria.
yield_strength = 300; % MPa
density = 7800; % kg/m^3
if yield_strength > 250 && density < 8000
disp('Material is acceptable.')
elseif yield_strength <= 250
disp('Yield strength is too low.')
else
disp('Density is too high.')
end
Material is acceptable.
Compound Conditions
Multiple conditions can be combined using logical operators.
&&is the logical AND (short-circuit)||is the logical OR (short-circuit)~is the logical NOT
Short-circuit operators stop evaluating as soon as the result is known, improving performance and avoiding errors.
Nested If Statements
You can nest if statements inside other if blocks, to handle more complex logic.
Each nested if must have its own end.
if x > 0
if x < 10
disp('x is between 0 and 10')
else
disp('x is greater than or equal to 10')
end
end
Error running matlab/conditionals_nested.m: Unrecognized function or variable 'x'.
A Few Tips
Writing else if as two words, rather than the single keyword elseif, is a common syntax error - MATLAB will treat it as a new, separate if statement that needs its own end, rather than a continuation of the outer one.
Prefer the short-circuit operators, && and ||, over & and | for compound conditions, since they stop evaluating as soon as the result is known.
Finally, if a nested if statement starts to grow several levels deep, it is often clearer to pull that logic out into its own function rather than keep nesting.
Reading Questions
- What is the purpose of an
ifstatement in MATLAB? - What happens if multiple conditions in an
if-elseif-elseblock are all true? - What is the difference between
&and&&in MATLAB? - How would you write a conditional statement that checks if the value
xis between 5 and 10, inclusive?
Practice Problem: Fuel Reserve Status
Pilots plan fuel around more than just “will I make it there.” Regulations require a minimum reserve in case of a diversion or delay, and how much time that reserve represents changes as fuel burns down.
In this practice problem, you’ll write a MATLAB script that classifies a fuel reserve as Normal, Caution, or Reserve based on how much flight time it represents.
Your Task
Write a script named fuel_reserve.m that starts from the given fuel state:
fuel_lb = 180; % lb, fuel remaining
burn_rate = 140; % lb/hr
Compute:
endurance_hr- the remaining flight time, in hours (fuel_lbdivided byburn_rate)status- a string classifyingendurance_hrusing anif-elseif-elsestatement:'Normal'ifendurance_hris 1.5 or more'Caution'ifendurance_hris at least 0.75 but less than 1.5'Reserve'ifendurance_hris less than 0.75
Your variable names for the two answers above must match exactly (endurance_hr, status) so that the checker below can find them.
Checking Your Work
Download check_fuel_reserve.m and save it in the same folder as your fuel_reserve.m script.
Make sure that folder is your Current Folder in MATLAB, then run:
>> check_fuel_reserve
The checker runs your script and reports whether each of the two values is correct. This is practice, not a graded assignment. If something doesn’t pass, use the feedback to find and fix the issue, then run the checker again.