0
0
MATLABdata~5 mins

If-elseif-else statements in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-elseif-else statements
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Checking conditions happens in a fixed sequence, no matter the input size.

Input Size (n)Approx. Operations
10Up to 3 checks
100Up to 3 checks
1000Up to 3 checks

Pattern observation: The number of checks stays the same regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if-elseif-else does not grow as input size grows.

Common Mistake

[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.

Interview Connect

Understanding that if-elseif-else statements run in constant time helps you explain simple decision-making code clearly and confidently.

Self-Check

"What if we added a loop around the if-elseif-else to check many numbers? How would the time complexity change?"