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?"
Practice
Solution
Step 1: Understand vectorization concept
Vectorization means applying operations to whole arrays at once, avoiding explicit loops.Step 2: Compare options
Only Performing operations on entire arrays at once without explicit loops describes this correctly; others describe loops or recursion.Final Answer:
Performing operations on entire arrays at once without explicit loops -> Option DQuick Check:
Vectorization = whole-array operations [OK]
- Confusing vectorization with loops
- Thinking recursion is vectorization
- Assuming manual indexing is vectorization
A using vectorization?Solution
Step 1: Identify vectorized sum syntax
MATLAB's built-insum()function sums all elements of an array directly.Step 2: Check options
sum = sum(A);usessum(A), which is vectorized.sum = 0; for i = 1:length(A); sum = sum + A(i); enduses a loop.sum = A + A;adds vector to itself.sum = A(1) + A(2);sums only two elements.Final Answer:
sum = sum(A); -> Option CQuick Check:
sum(A) sums all elements vectorized [OK]
- Using loops instead of sum()
- Adding vector to itself instead of summing
- Summing only part of the vector
A = [1, 2, 3, 4]; B = A .* 2;
Solution
Step 1: Understand element-wise multiplication
The operator.*multiplies each element ofAby 2 individually.Step 2: Calculate each element
1*2=2, 2*2=4, 3*2=6, 4*2=8, soB = [2, 4, 6, 8].Final Answer:
[2, 4, 6, 8] -> Option BQuick Check:
Element-wise multiply by 2 = [2,4,6,8] [OK]
- Confusing .* with matrix multiplication (*)
- Expecting squared values instead of doubled
- Thinking it causes dimension errors
A:A = [1, 2, 3]; for i = 1:length(A); A = A * 2; end
Solution
Step 1: Analyze the loop body
The code multiplies entire vectorAby 2 each iteration, ignoringi.Step 2: Understand the effect
Sinceiis unused, the loop repeats the same operation, scalingAmultiple times (by 8 total) instead of doubling individual elements via indexing.Final Answer:
The loop variableiis not used inside the loop -> Option AQuick Check:
Loop variable unused causes logic error [OK]
- Ignoring loop variable usage
- Confusing * and .* operators
- Assuming vector auto-updates element-wise
X efficiently. Which MATLAB code snippet uses vectorization correctly?Solution
Step 1: Understand vectorized squaring
Element-wise multiplication.*betweenXandXsquares each element efficiently.Step 2: Check each option
for i = 1:length(X); Y(i) = X(i)^2; enduses a loop (less efficient).Y = zeros(size(X)); for i = 1:length(X); Y = X(i)^2; endoverwritesYwith a scalar each iteration.Y = X ^ 2;attempts invalid matrix power for vectors.Y = X .* X;is correct.Final Answer:
Y = X .* X; -> Option AQuick Check:
Element-wise multiply vector by itself = square [OK]
- Using ^ instead of .^ or .* for element-wise power
- Overwriting output inside loop
- Using loops instead of vectorization
Ready to prove it?
Pass the test and this pattern moves unknown
