Loops

for k = values assigns each column of values to k in turn.

Concept

for k = values assigns each column of values to k in turn. For a row vector that means each element; for a matrix, each column (a surprise for beginners).

while condition ... end repeats while the condition is true; make sure something inside changes the condition.

break exits the innermost loop; continue skips to the next iteration. There is no do…while; use while true ... if done, break, end, end.

Loops vs Vectorization MATLAB's built-in array operations run in optimized compiled code, so a vectorized expression (sum((1:1e6).^2)) is usually much faster and shorter than an explicit loop. Modern MATLAB's JIT compiler has narrowed the gap, but vectorized code is still idiomatic. When a loop is necessary (each step depends on the previous one), preallocate the result array (Module 13).

Why It Matters

Simulations that step through time (numerical integration, controllers, state machines) need loops; data processing usually doesn't. Knowing which is which is key to fast MATLAB.

Syntax

for k = 1:n, ... end
for k = n:-1:1, ... end
while err > tol, ... end

Example

10.1 for, while, break, continue, preallocation and vectorization

total = 0;
for k = 1:5
    total = total + k;
end
fprintf('sum 1..5 with for = %d\n', total)

for col = [1 2; 3 4]               % a for loop over a matrix iterates over COLUMNS
    fprintf('column: %s\n', mat2str(col'))
end

n = 0; x = 1000;
while x > 1
    x = x / 2;
    n = n + 1;
end
fprintf('halving 1000 until <= 1 took %d steps (x = %.4f)\n', n, x)

for k = 1:10
    if mod(k, 2) == 0, continue, end
    if k > 7, break, end
    fprintf('%d ', k)
end
fprintf('\n')

fib = zeros(1, 10);                % preallocate
fib(1:2) = 1;
for k = 3:10
    fib(k) = fib(k - 1) + fib(k - 2);
end
fprintf('Fibonacci: %s\n', mat2str(fib))

tic
s = 0;
for k = 1:1e6
    s = s + k^2;
end
t_loop = toc;
tic
s2 = sum((1:1e6).^2);
t_vec = toc;
fprintf('loop sum %g, vectorized sum %g, same: %d, vectorized faster: %d\n', s, s2, s == s2, t_vec < t_loop)

Expected Result

Iterating over a 2×2 matrix visited its columns. The loop and the vectorized sum give the same number; the vectorized version was faster. (Timings vary; in MATLAB the JIT makes simple loops faster than in Octave, but vectorized code remains the idiom.)

sum 1..5 with for = 15
column: [1 3]
column: [2 4]
halving 1000 until <= 1 took 10 steps (x = 0.9766)
1 3 5 7 
Fibonacci: [1 1 2 3 5 8 13 21 34 55]
loop sum 3.33334e+17, vectorized sum 3.33334e+17, same: 1, vectorized faster: 1

Common Mistakes

Infinite while loops (condition never changes); stop with Ctrl+C.

Growing arrays inside loops without preallocation.

Modifying the loop variable inside a for loop (it is reset each iteration).

Iterating over a column vector with for and getting the whole vector at once.

Best Practices

Vectorize where natural; loop where each step depends on the previous one.

Preallocate: result = zeros(1, n).

Use numel(v) in 1:numel(v) rather than length(v) for clarity with matrices.

Interview Relevance

High for MATLAB roles: "for vs while?", "what does a for loop over a matrix do?", "why vectorize?", "why preallocate?".

Practice Questions

Print the multiplication table of 7 with a loop.

Find the first Fibonacci number greater than 1000 with a while loop.

Sum only the odd numbers 1..99 with continue.

Rewrite Question 3 without a loop.

Quick Quiz

Q1. (Multiple choice) for c = [1 2; 3 4] iterates over: A) Elements B) Rows C) Columns D) Nothing — error Answer: C (verified).

Q2. (Predict the output) The example's break/continue loop printed which numbers?

Answer: 1 3 5 7 (verified).

Q3. (True/False) MATLAB has a do…while loop.

Answer: False. Use while true … break … end.

Q4. (Find the bug) x = 10; while x > 0, disp(x); end Answer: x never changes → infinite loop. Add x = x - 1;.

Coding Challenge

Use a while loop to find how many years it takes for 1000 at 7% annual interest to double, then verify with the formula log(2) / log(1.07).

balance = 1000; years = 0;
while balance < 2000
    balance = balance * 1.07;
    years = years + 1;
end
fprintf('doubles after %d years (balance %.2f)\n', years, balance)
fprintf('formula: %.2f years\n', log(2) / log(1.07))