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.