For loops in MATLAB - Time & Space 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?
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 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.
As n gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: If you double n, the number of operations also doubles. The growth is steady and direct.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the size of n.
[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.
Knowing how loops affect running time helps you explain your code clearly and shows you understand how programs work as they grow.
"What if we added a second nested for loop inside the first? How would the time complexity change?"