Concept Flow - Vectorization vs loops
Start
Input Data
Choose Method
Loop
Process
Output
End
This flow shows how data can be processed either by loops or vectorized operations, both leading to the output.
A = 1:5; B = zeros(1,5); for i = 1:5 B(i) = A(i)^2; end
| Iteration | i | A(i) | Condition i<=5 | Action | B after action |
|---|---|---|---|---|---|
| 1 | 1 | 1 | True | B(1) = 1^2 = 1 | [1 0 0 0 0] |
| 2 | 2 | 2 | True | B(2) = 2^2 = 4 | [1 4 0 0 0] |
| 3 | 3 | 3 | True | B(3) = 3^2 = 9 | [1 4 9 0 0] |
| 4 | 4 | 4 | True | B(4) = 4^2 = 16 | [1 4 9 16 0] |
| 5 | 5 | 5 | True | B(5) = 5^2 = 25 | [1 4 9 16 25] |
| 6 | 6 | - | False | Exit loop | [1 4 9 16 25] |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | After 5 | Final |
|---|---|---|---|---|---|---|---|
| i | - | 1 | 2 | 3 | 4 | 5 | 6 |
| B | [0 0 0 0 0] | [1 0 0 0 0] | [1 4 0 0 0] | [1 4 9 0 0] | [1 4 9 16 0] | [1 4 9 16 25] | [1 4 9 16 25] |
Vectorization vs loops in MATLAB: - Loops process elements one by one. - Vectorization applies operations to whole arrays at once. - Vectorized code is usually faster and cleaner. - Use vectorization when possible for efficiency. - Loops are easier to understand but slower for large data.
A using vectorization?sum() function sums all elements of an array directly.sum = sum(A); uses sum(A), which is vectorized. sum = 0; for i = 1:length(A); sum = sum + A(i); end uses a loop. sum = A + A; adds vector to itself. sum = A(1) + A(2); sums only two elements.A = [1, 2, 3, 4]; B = A .* 2;
.* multiplies each element of A by 2 individually.B = [2, 4, 6, 8].A:A = [1, 2, 3]; for i = 1:length(A); A = A * 2; end
A by 2 each iteration, ignoring i.i is unused, the loop repeats the same operation, scaling A multiple times (by 8 total) instead of doubling individual elements via indexing.i is not used inside the loop -> Option AX efficiently. Which MATLAB code snippet uses vectorization correctly?.* between X and X squares each element efficiently.for i = 1:length(X); Y(i) = X(i)^2; end uses a loop (less efficient). Y = zeros(size(X)); for i = 1:length(X); Y = X(i)^2; end overwrites Y with a scalar each iteration. Y = X ^ 2; attempts invalid matrix power for vectors. Y = X .* X; is correct.Pass the test and this pattern moves unknown