Script files and editor in MATLAB - Time & Space Complexity
When we run a script file in MATLAB, it executes commands one by one. Understanding how long this takes helps us write faster scripts.
We want to know how the time to run the script changes as the input size grows.
Analyze the time complexity of the following MATLAB script.
% Script to sum numbers from 1 to n
n = 1000;
sumVal = 0;
for i = 1:n
sumVal = sumVal + i;
end
This script adds all numbers from 1 up to n using a loop.
Look for repeated actions in the script.
- Primary operation: The addition inside the for-loop.
- How many times: Exactly n times, once for each number from 1 to n.
As n gets bigger, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: If you double n, the work doubles too.
Time Complexity: O(n)
This means the time to run the script grows in direct proportion to the input size.
[X] Wrong: "The script runs instantly no matter how big n is."
[OK] Correct: Each number must be added one by one, so bigger n means more work and more time.
Knowing how loops affect time helps you write efficient scripts and explain your code clearly in conversations.
"What if we replaced the for-loop with a built-in sum function? How would the time complexity change?"