Variable creation and assignment in MATLAB - Time & Space Complexity
We want to see how long it takes to create and assign variables in MATLAB as the input size changes.
How does the time needed grow when we make more variables or bigger ones?
Analyze the time complexity of the following code snippet.
n = 1000;
A = zeros(1, n);
for i = 1:n
A(i) = i;
end
This code creates an array of size n and assigns values to each element one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Assigning a value to each element of the array inside the loop.
- How many times: The loop runs n times, so the assignment happens n times.
As n grows, the number of assignments grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to create and assign values grows in a straight line as the number of elements increases.
[X] Wrong: "Creating and assigning variables always takes the same time no matter how big the data is."
[OK] Correct: Actually, when you assign many values, the time grows with how many values you assign, so bigger arrays take more time.
Understanding how simple operations like variable assignment scale helps you explain code efficiency clearly and confidently.
"What if we replaced the for-loop with a vectorized assignment like A = 1:n; How would the time complexity change?"