for Loops and Ranges
A for loop in MATLAB iterates its loop variable over the columns of whatever you give it — most commonly a numeric range like 1:20, but it can also step through the columns of a matrix or the entries of a cell array. The syntax for i = 1:n ... end runs the body once for each value from 1 to n. Unlike some languages, the loop variable persists after the loop ends and holds its final value.
Cricket analogy: for over = 1:20 steps through each over of a T20 innings exactly once, the way a scorer logs figures over after over
while Loops, break, and continue
A while loop repeats as long as its condition remains true, useful when the number of iterations isn't known in advance. break immediately exits the innermost loop, and continue skips the rest of the current iteration and jumps to the next condition check. Both work identically inside for and while loops.
Cricket analogy: a while loop keeps bowling while wicketsLost<10 && oversLeft>0, and a break fires the instant all-out happens mid-over
% Preallocated race split analysis
numLaps = 10;
splits = zeros(1, numLaps);
for lap = 1:numLaps
splits(lap) = 60 + randn()*2; % simulated lap time in seconds
end
totalTime = 0;
lapIdx = 0;
while lapIdx < numLaps
lapIdx = lapIdx + 1;
if splits(lapIdx) > 65
continue; % skip anomalously slow laps in the running total
end
totalTime = totalTime + splits(lapIdx);
if totalTime > 550
break; % stop once cumulative time exceeds target
end
endNested Loops, Preallocation, and Vectorization
Nested loops (a loop inside another loop) are sometimes unavoidable, but MATLAB's JIT compiler still processes each iteration with overhead, so deeply nested loops over large arrays are slow. Two mitigations: preallocate arrays with zeros(), ones(), or cell() before a loop rather than letting them grow one element at a time (which forces repeated memory reallocation and triggers MATLAB's array-growth warning), and prefer vectorized operations over explicit loops wherever the operation can be expressed that way.
Cricket analogy: nested loops over for team = 1:2 and for player = 1:11 to tally every batsman's runs per team are far slower than preallocating a scoreboard matrix and filling it vectorized
MATLAB's Editor flags growing arrays inside loops (e.g. results(end+1) = x) with an orange warning underline. This isn't cosmetic — for large iteration counts, preallocating with zeros() or cell() can be an order of magnitude faster.
Looping Over Cell Arrays and Structs
Cell arrays and struct arrays often hold heterogeneous data (like names paired with numeric metadata), so a common pattern is for i = 1:numel(cellArray) to index by position, then access parallel struct fields inside the loop body. numel() is preferred over length() for this because it correctly reports the total element count regardless of array shape.
Cricket analogy: for i = 1:numel(playerNames) loops through a cell array of player name strings to print each one's batting average from a matching struct array
Modifying the loop variable inside a for loop body does not change which values MATLAB iterates over — the range 1:n is evaluated once up front. If you need to skip ahead dynamically, use a while loop instead.
- for i = range ... end iterates the loop variable over columns of a range, matrix, or cell array.
- while condition ... end repeats until the condition becomes false; the iteration count need not be known in advance.
- break exits the innermost loop immediately; continue skips to the next iteration's condition check.
- Preallocate arrays with zeros()/cell() before a loop to avoid the performance cost of growing arrays element by element.
- Vectorized operations usually outperform explicit loops for array-wide computations.
- numel() is the idiomatic way to get the loop bound for cell arrays and struct arrays.
- Changing the for loop variable inside the body doesn't affect the predetermined iteration sequence.
Practice what you learned
1. What determines how many times a MATLAB for loop executes?
2. Which statement immediately exits the innermost loop?
3. Why should arrays be preallocated before a loop that fills them?
4. What does numel() return for a cell array?
5. Inside a for loop, if you reassign the loop variable to a different value, what happens?
Was this page helpful?
You May Also Like
Conditionals in MATLAB
Learn how MATLAB branches program flow with if/elseif/else, comparison and logical operators, switch-case, and vectorized alternatives like any() and all().
Functions in MATLAB
Learn how to define MATLAB functions with proper file naming, multiple return values, variable input arguments, local function scope, and recursion.
Anonymous Functions and Function Handles
Understand MATLAB's @ syntax for anonymous functions and function handles, closures over workspace variables, and passing handles to arrayfun, cellfun, ode45, and fplot.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics