Why control flow directs program logic in MATLAB - Performance Analysis
Control flow decides which parts of a program run and how often. Understanding its time cost helps us see how program speed changes with input size.
We want to know how the program's running time grows when control flow changes the path of execution.
Analyze the time complexity of the following code snippet.
for i = 1:n
if mod(i,2) == 0
disp(i)
else
disp(i^2)
end
end
This code loops from 1 to n and uses an if-else to decide what to display for each number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 1 to n.
- How many times: Exactly n times, once per number.
Each number from 1 to n is checked and displayed once, so work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks and displays |
| 100 | 100 checks and displays |
| 1000 | 1000 checks and displays |
Pattern observation: The number of operations grows steadily as n grows; doubling n doubles the work.
Time Complexity: O(n)
This means the program takes longer in direct proportion to the input size.
[X] Wrong: "The if-else inside the loop doubles the time because it has two paths."
[OK] Correct: The if-else only chooses one path each time, so it does not multiply the work; it still runs once per loop.
Understanding how control flow affects time helps you explain program speed clearly and shows you can think about efficiency in real code.
"What if the loop contained another nested loop inside the if-branch? How would the time complexity change?"