Vectorization vs loops in MATLAB - Performance Comparison
We want to see how using vectorization or loops affects how long a MATLAB program takes to run.
How does the time needed change when we do the same task with loops versus vectorized code?
Analyze the time complexity of the following code snippet.
n = 1000;
result = zeros(1,n);
for i = 1:n
result(i) = i^2;
end
% Vectorized version
result_vec = (1:n).^2;
This code calculates the squares of numbers from 1 to n using a loop and then using vectorization.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop runs from 1 to n, doing one multiplication each time.
- How many times: The loop runs exactly n times.
- Vectorized operation: The whole array is squared in one step without explicit looping.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations (Loop) | Approx. Operations (Vectorized) |
|---|---|---|
| 10 | 10 multiplications | 1 vector operation on 10 elements |
| 100 | 100 multiplications | 1 vector operation on 100 elements |
| 1000 | 1000 multiplications | 1 vector operation on 1000 elements |
Pattern observation: The loop does more steps as n grows, while vectorization handles all at once, so it grows slower in time.
Time Complexity: O(n)
This means the time grows in a straight line with the number of elements when using loops, but vectorization can be faster by doing many operations together.
[X] Wrong: "Vectorization always means the program runs in constant time no matter how big n is."
[OK] Correct: Vectorization still processes all elements, so time grows with n, but it uses faster internal operations than loops.
Understanding how loops and vectorization affect time helps you write faster MATLAB code and shows you can think about efficiency clearly.
"What if we replaced the loop with a nested loop that squares numbers in a 2D matrix? How would the time complexity change?"