Imagine you want to print the message βHello!β five times. Without loops, you would write the same command repeatedly. With a loop, it is much cleaner:
The for-loop version is shorter, clearer, and easier to modify. If you later need 100 repetitions instead of 5, you only change one number rather than copying and pasting 95 more lines.
A for-loop repeats a block of code once for each value in a specified list. This is the right tool when you know in advance how many times you want to repeat some code.
Here is a concrete example showing repeated calculations. Suppose you want to compute and display several powers of 2. Without a loop, you must explicitly write each calculation:
n = 1;
x = 2^n;
fprintf('2^%i = %i\n', n, x)
n = 2;
x = 2^n;
fprintf('2^%i = %i\n', n, x)
n = 3;
x = 2^n;
fprintf('2^%i = %i\n', n, x)
n = 4;
x = 2^n;
fprintf('2^%i = %i\n', n, x)
n = 5;
x = 2^n;
fprintf('2^%i = %i\n', n, x)
for n = 1:5
x = 2^n;
fprintf('2^%i = %i\n', n, x)
end
Both versions produce the same output: 2^1 = 2, 2^2 = 4, 2^3 = 8, 2^4 = 16, and 2^5 = 32. The loop version eliminates redundancy by automatically updating the loop variable n from 1 to 5.
Before writing a loop, identify: (1) what changes each iteration (the loop variable), and (2) what you want to update as the loop runs (for example, a running total or an output variable).
totalsum = 0; % initialize
for i = 1:5
totalsum = totalsum + i;
end
fprintf('Total sum: %i\n', totalsum)
The variable totalsum starts at 0, then adds 1, then 2, and so on, reaching 15. Compare this to MATLABβs built-in sum(1:5), which gives the same result. The loop version shows you the logic step by step.
N = 10;
sum_total = 0;
prod_total = 1;
for k = 1:N
sum_total = sum_total + k;
prod_total = prod_total * k;
end
sum_total
prod_total
After the loop completes, sum_total holds \(1+2+\cdots+10=55\text{,}\) and prod_total holds \(1\cdot 2\cdot\cdots\cdot 10=3628800\) (which is \(10!\)).