Coding

MATLAB for Loop: Syntax, Step Values and Examples

A MATLAB for loop repeats a block of statements once for each value in a range or array: for k = 1:5 runs the body five times with k set to 1, 2, 3, 4 and 5, and the block ends with end. This page covers the three forms of the loop values, counting down, looping over matrix columns, break, continue and preallocation.

MATLAB for loop syntax

The general form is:

for index = values
    statements
end

Here index is the loop variable and values decides how many times the body runs and what index holds on each pass. MathWorks documents three forms for values:

FormWhat the index does
initVal:endValStarts at initVal and increases by 1 until it passes endVal.
initVal:step:endValChanges by step on each pass. A negative step counts down.
valArrayTakes one column of the array per pass. The first pass uses valArray(:,1).

The simplest case is a counter. Typing this at the command window or in a script prints the squares of 1 to 5:

for k = 1:5
    disp(k^2)
end

Example output:

     1
     4
     9
    16
    25

Unlike many languages, there are no parentheses around the header and no braces. The loop closes with end, and indenting the body is a convention that makes nesting readable, not a requirement.

Step values and counting down

Put the step in the middle of the range. A step of 2 visits every second value, and a negative step counts down:

for k = 10:-2:2
    disp(k)
end

This prints 10, 8, 6, 4 and 2. The step does not have to be a whole number. The MathWorks reference uses this fractional example:

for v = 1.0:-0.2:0.0
   disp(v)
end

Its output is 1, 0.8000, 0.6000, 0.4000, 0.2000 and 0. Fractional steps are stored as binary floating-point numbers, so if you need an exact count of iterations, loop over integers and compute the fractional value inside the body (for example x = k/10).

Looping over a list of values

If you already have the values you want, put them in a row vector and use it directly:

for v = [1 5 8 17]
   disp(v)
end

This runs four times and prints 1, 5, 8 and 17. The values do not need to follow a pattern, which is the main reason to prefer this form over a range.

How a for loop treats matrices and column vectors

This is the point that surprises most people. When values is an array, MATLAB gives the loop one column at a time, so the loop runs once per column, not once per element. The maximum number of iterations is numel(valArray(1,:)), which is the number of columns. MathWorks demonstrates it with a 4-by-3 matrix, which gives three iterations:

for I = eye(4,3)
    disp('Current unit vector:')
    disp(I)
end

On each pass I is a 4-by-1 column: first [1;0;0;0], then [0;1;0;0], then [0;0;1;0].

The same rule explains a common bug. A column vector such as [1;2;3] has a single column, so the loop runs once and the index is the entire vector. To step through its elements, transpose it first:

v = [10; 20; 30];
for x = v'
    disp(x)
end

Now v' is a row vector and x takes the values 10, 20 and 30 in turn. The array can be of any data type, including a character vector, a cell array or a struct. Because the column rule still applies, looping over a cell array gives you a cell (a column of the cell array) on each pass, not the value inside it. Index into it with braces, for example x{1}, to get the content.

Nested loops

A loop can contain another loop, and each one needs its own end. The MathWorks reference builds a 10-by-10 Hilbert matrix this way:

s = 10;
H = zeros(s);

for c = 1:s
    for r = 1:s
        H(r,c) = 1/(r+c-1);
    end
end

The inner loop runs completely for every pass of the outer loop, so the body executes 100 times. The outer loop walks the columns and the inner loop the rows, which also matches how MATLAB stores matrices in memory, column by column.

Exit early with break and skip with continue

Two statements change the normal flow of a loop:

  • break exits the loop early. Execution resumes after the loop's end.
  • continue skips the remaining statements in the current iteration and starts the next one.

A short example that stops at the first value over a limit and ignores negative numbers:

readings = [4 -1 7 12 3];
total = 0;
for r = readings
    if r < 0
        continue
    end
    if r > 10
        break
    end
    total = total + r;
end
disp(total)

The loop adds 4, skips -1, adds 7, then hits 12 and stops, so it prints 11. The MathWorks loop-control page shows both statements together in a while loop that counts the comment lines at the top of a file, using break at the first empty line and continue for lines that do not start with %.

Preallocate arrays you fill in a loop

If a loop writes one result per iteration, create the output array at full size before the loop. Growing an array inside the loop forces MATLAB to find new memory and copy the data over and over. MathWorks times a loop that computes x(k) = x(k-1) + 5 for one million elements:

VersionTime in the MathWorks test
x grows on every pass0.301528 s
x = zeros(1,1000000); before the loop0.011938 s

That is roughly 25 times faster. The page does not state the hardware, so treat the ratio as indicative and expect different absolute times on your machine. Use zeros for numeric arrays, strings for string arrays and cell for cell arrays. For a non-double type, create it directly, for example zeros(100,'int8') rather than int8(zeros(100)), which builds a double matrix first and then converts it.

The Hilbert example above already does this with H = zeros(s).

Mistakes to avoid

  • Assigning to the index. MathWorks advises against changing the loop variable inside the loop, because the next iteration overrides it. Copy it to a second variable if you need to modify it.
  • Looping over a column vector. It runs once. Transpose it, or loop over 1:numel(v) and use v(k).
  • Forgetting end. Every for, if and while block needs one. A missing end usually produces a parse error when the file runs.
  • Using a loop where a vectorized expression works. y = x.^2 squares every element of x without a loop. Use a loop when each iteration depends on the previous one, or when the body does something that cannot be written as one array operation.

For comparison with another language's loop syntax, see Bash for loop examples.

Frequently asked questions

How do I make a MATLAB for loop count down?
Use a negative step in the range: for k = 10:-1:1. The index starts at 10 and decreases by 1 on each pass until it would go below 1. The step can also be fractional, for example 1.0:-0.2:0.0.
Why does my for loop run only once over a column vector?
When the values are an array, MATLAB assigns one column per iteration. A column vector has one column, so the loop runs once and the index holds the whole vector. Transpose it with v' to get a row vector and the loop will visit each element.
What is the difference between break and continue in MATLAB?
break exits the loop immediately and execution resumes after the end keyword. continue skips the rest of the current iteration and starts the next one with the next index value.
Should I change the loop variable inside a for loop?
No. MathWorks advises against assigning to the index variable inside the loop, because the for statement overrides the change at the start of the next iteration. Copy the value to another variable if you need to modify it.

Sources