0
0
MATLABdata~5 mins

For loops in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For loops
O(n)
Understanding Time Complexity

When we use for loops in MATLAB, the program repeats some actions many times. Understanding how this repetition affects the time it takes to run helps us write better code.

We want to know: how does the running time grow when the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

for i = 1:n
    disp(i);
end
    

This code prints numbers from 1 to n, repeating the display action n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The disp(i) command inside the for loop.
  • How many times: It runs exactly n times, once for each number from 1 to n.
How Execution Grows With Input

As n gets bigger, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: If you double n, the number of operations also doubles. The growth is steady and direct.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line with the size of n.

Common Mistake

[X] Wrong: "The loop runs faster because it just prints numbers."

[OK] Correct: Even simple actions inside the loop add up. The total time depends on how many times the loop runs, not just what it does each time.

Interview Connect

Knowing how loops affect running time helps you explain your code clearly and shows you understand how programs work as they grow.

Self-Check

"What if we added a second nested for loop inside the first? How would the time complexity change?"