Conditional Statements and Loops
MATLAB Control Flow: Decisions and Repetition
MATLAB Control Flow determines which statements execute and how often they execute. When programming in MATLAB, you use conditional statements to choose actions and loops to repeat calculations. These structures let an engineering calculation respond to changing measurements, process scheduled operations, or stop when a target is reached. The examples here use scalar conditions so each decision has one clear true-or-false result.
Choose a branch
A branch is an alternative execution path selected by a condition. An if statement tests its condition first. If that condition is false, MATLAB tests any elseif conditions in order. It executes the first matching branch and then continues after end. An optional else handles cases where all preceding tests are false.
speed = 9; % m/s
if speed >= 12
command = 'stop';
elseif speed >= 6
command = 'slow';
else
command = 'run';
endHere, speed >= 12 is false and speed >= 6 is true, so command becomes 'slow'. Even if several conditions could be true, one if–elseif chain executes only its first matching branch. Separate if statements instead make separate decisions and may execute several bodies.
Use == to compare equality and ~= to compare inequality; = assigns a value. Other scalar comparisons include <, <=, >, and >=. For two scalar requirements, && means both must hold, while || means at least one must hold. For example, (speed >= 6) && (speed < 12) describes an interval explicitly.
Repeat a calculation
An iteration is one execution of a loop body. A for loop visits a specified sequence of values. For example, for k = 2:2:8 visits 2, 4, 6, and 8: start, step, and endpoint determine the sequence. The endpoint is included when the step reaches it.
Many engineering loops update a stored quantity. For a constant power during each time interval, the energy update is
where E is energy in joules, Pk is power in watts during interval k, and Δt is the interval duration in seconds.
energy = 0; % J
for k = 1:3
energy = energy + 40*2; % W multiplied by s
endEach iteration adds 80 J, giving 240 J after three iterations. Initialize an accumulated quantity before the loop. Initializing it inside the body would erase earlier contributions.
A while loop repeats while its condition remains true. MATLAB checks the condition before the first iteration and again before every subsequent iteration. Consequently, the body can execute zero times.
Use while when a changing state determines whether another repetition is needed. Initialize every variable used in the condition, then ensure the execution paths can make progress toward termination. A loop can run indefinitely if its condition stays true and no break or other exit is reached.
Control progress and termination
Choose a structure according to the decision you need to express.
Structure | Execution rule | Typical use |
|---|---|---|
if–elseif–else | Select one matching branch | Choose an operating state |
for | Visit a specified sequence | Process scheduled steps |
while | Repeat while a condition is true | Continue toward a target |
break | Exit the innermost enclosing loop | Stop after a terminating event |
continue | Skip the rest of the current iteration | Reject an invalid reading |
After break, execution resumes after that loop's end. After continue, a for loop advances to its next scheduled value; a while loop returns to its condition test. Statements skipped by continue include any updates below it, so update placement matters.
Each nested if, for, or while needs its own end. Indentation makes these boundaries easier to inspect, but end determines the structure.
What to remember
- An if chain executes its first matching branch.
- Initialize accumulators before repetition begins.
- A for loop follows a sequence; a while loop retests a condition.
- Check equality boundaries and every path that skips an update.
- break exits a loop; continue skips the current iteration's remaining statements.
Example: Controlling a Batch Dispenser
A dispenser adds granules to a hopper in complete pulses. Each pulse delivers exactly 1.8 kg and takes 3.0 s. Assume there are no losses, no delays between pulses, and no partial pulses. The desired batch mass is at least 8.0 kg, and the hopper capacity is 9.0 kg.
For a measured mass below 8.0 kg, the controller should select 'fill'. From 8.0 kg through 9.0 kg inclusive, it should select 'hold'. Above 9.0 kg, it should select 'overfill'.
Each part starts independently.
a) Write an if–elseif–else statement implementing these rules. Determine the command when the measured mass is exactly 8.0 kg.
Test the lower boundary first, then distinguish an acceptable batch from an overfilled hopper. Here, mass stores the measurement in kg.
At 8.0 kg, mass < 8.0 is false. The next condition, mass <= 9.0, is true. Therefore, the command is 'hold'. Reaching the elseif already establishes that the mass is at least 8.0 kg, so this branch covers the entire required interval.
The MATLAB implementation is:
mass = 8.0; % kg
if mass < 8.0
command = 'fill';
elseif mass <= 9.0
command = 'hold';
else
command = 'overfill';
endb) Starting with 1.0 kg in the hopper, write a for loop that delivers exactly three pulses. Calculate the final mass and elapsed dispensing time.
Initialize mass and time before the loop so each pulse adds to the values left by the previous pulse. The sequence 1:3 schedules exactly three iterations.
Each iteration increases the mass by 1.8 kg and the elapsed time by 3.0 s. Thus,
The final mass is 6.4 kg, and dispensing takes 9.0 s. A fixed three-pulse schedule does not reach the 8.0 kg target.
The MATLAB implementation is:
mass = 1.0; % kg
time = 0; % s
for pulse = 1:3
mass = mass + 1.8;
time = time + 3.0;
endTracing the initial state and the state after each iteration gives:
- After 0 completed pulses: hopper mass is 1.0 kg and elapsed time is 0.0 s.
- After 1 completed pulse: hopper mass is ________ and elapsed time is 3.0 s.
- After 2 completed pulses: hopper mass is ________ and elapsed time is 6.0 s.
- After 3 completed pulses: hopper mass is 6.4 kg and elapsed time is 9.0 s.
c) Starting again with 1.0 kg, write a while loop that delivers complete pulses until the mass first reaches at least 8.0 kg. Find the number of pulses, final mass, and elapsed time. Check the hopper capacity.
Use the test-before-iteration order shown below when tracing the loop.
The continuation condition should express that another pulse is needed: the current mass is below 8.0 kg. Update mass, time, and the pulse counter during every iteration.
After successive pulses, the masses are 2.8, 4.6, 6.4, and 8.2 kg. The condition remains true at 6.4 kg, so the fourth pulse executes. At the next test, 8.2 kg is not below 8.0 kg, and execution stops.
The final batch is 8.2 kg after four pulses and 12.0 s. It exceeds the target by 0.2 kg because only complete pulses are available. It remains 9.0−8.2=0.8 kg below capacity. This capacity check follows from the supplied numbers; the loop itself tests only the target mass.
The MATLAB implementation is:
mass = 1.0; % kg
time = 0; % s
pulses = 0;
while mass < 8.0
mass = mass + 1.8;
time = time + 3.0;
pulses = pulses + 1;
endA loop repeats a block of code. An engineer is choosing MATLAB keywords for two measurement tasks. Complete each statement with for or while, using the structure that directly expresses the stated repetition requirement.
To measure vibration once at each frequency in the supplied sequence 20:5:50, use a loop.
To keep taking temperature readings while the latest reading exceeds 40 °C, with no predetermined number of readings, use a loop.
A MATLAB script adds the energy from four scheduled actuator pulses. For each visited value of k, the pulse contributes 2*k joules.
energy = 0; % J
for k = 1:2:7
energy = energy + 2*k;
endWhat is the final value of energy?