If-elseif-else statements in MATLAB - Time & Space Complexity
We want to see how the time to run if-elseif-else statements changes as input changes.
Specifically, we ask: does checking conditions take more time when inputs grow?
Analyze the time complexity of the following code snippet.
x = randi(100);
if x < 10
disp('Less than 10');
elseif x < 50
disp('Between 10 and 49');
else
disp('50 or more');
end
This code checks a number and prints a message based on which range it falls into.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions in if-elseif-else statements.
- How many times: Each condition is checked at most once in order until one matches.
Checking conditions happens in a fixed sequence, no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 3 checks |
| 100 | Up to 3 checks |
| 1000 | Up to 3 checks |
Pattern observation: The number of checks stays the same regardless of input size.
Time Complexity: O(1)
This means the time to run the if-elseif-else does not grow as input size grows.
[X] Wrong: "If statements take longer when numbers get bigger because there are more possibilities."
[OK] Correct: The number of conditions checked is fixed and does not depend on the size of the number, only on how many conditions you wrote.
Understanding that if-elseif-else statements run in constant time helps you explain simple decision-making code clearly and confidently.
"What if we added a loop around the if-elseif-else to check many numbers? How would the time complexity change?"