First MATLAB program - Time & Space Complexity
When we write our first MATLAB program, it is helpful to see how the time it takes to run changes as we give it more work.
We want to know how the program's running time grows when the input size gets bigger.
Analyze the time complexity of the following code snippet.
n = 10;
total = 0;
for i = 1:n
total = total + i;
end
disp(total);
This code adds up all numbers from 1 to n and shows the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds each number to total.
- How many times: It runs 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: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the input.
[X] Wrong: "The loop runs faster because it just adds numbers."
[OK] Correct: Even simple additions take time, and since the loop runs n times, the total time grows with n.
Understanding how loops affect running time is a key skill. It helps you explain your code clearly and shows you can think about efficiency.
"What if we changed the loop to run from 1 to n squared? How would the time complexity change?"