Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

Loops in MATLAB: for, while and How to Stop Them

How MATLAB for and while loops work, why matrices loop per column, and how to stop a loop with break or Ctrl+C, with Octave, Python and R equivalents.

Written and maintained by CASRAI Editorial Board

Last updated

Loops in MATLAB repeat a block of statements. You write them with the for keyword (a fixed set of values) or the while keyword (repeat while a condition holds), and each closes with end. This page gives the exact syntax from MathWorks’ reference pages, the column-iteration rule that surprises most beginners, and the ways to stop a loop that is running. It is written for researchers and analysts who need a loop to run correctly the first time.

What are loops in MATLAB and what are they used for in research?

A loop runs the same statements repeatedly. In MATLAB the two loop constructs are for, which runs a set number of times over a list of values, and while, which runs for as long as a condition is true. In research code, loops typically process one file, subject, parameter value or simulation run per pass, or iterate an algorithm until it converges. Both constructs are documented by MathWorks on the for and while reference pages (checked 2026-11-07).

Is there a loop() function? Loops are created with the for and while keywords, not by calling a function named loop. Search the two reference pages above for the exact keyword you need.

Install or access (official source only)

MATLAB is a MathWorks product, so the loop keywords and their behaviour are defined by the MathWorks documentation at mathworks.com/help/matlab. Your institution’s licensing arrangements determine how you obtain it. If you do not have access, the free alternatives table below shows the equivalent loop syntax in GNU Octave, Python and R.

For loop syntax

A for loop has the form below. MathWorks defines it as a loop that executes statements for each value of the index.

for index = values
    statements
end

The values part can take three forms, all from the for reference page:

  • initVal:endVal increments the index by 1 on each iteration.
  • initVal:step:endVal increments the index by step on each iteration, or decrements it when step is negative. For example, 1.0:-0.2:0.0 gives the index values 1, 0.8, 0.6, 0.4, 0.2 and 0.
  • valArray creates a column vector index from subsequent columns of the array on each iteration.

For loop in MATLAB: a worked example

This loop visits the values in a row vector, one per pass. The vector [1 5 8 17] is one of the examples on the MathWorks page.

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

The body runs four times, with v equal to 1, then 5, then 8, then 17.

The column rule: matrices loop per column

When values is an array, the loop runs once per column, and the index is that column as a column vector. MathWorks’ example is eye(4,3), a 4-by-3 matrix, so the loop runs 3 times. Per the same page, to iterate over the values of a single column vector you must transpose it first, because a column vector has only one column and would run the body once.

x = [10; 20; 30];   % column vector
for v = x'          % transpose so each value is a column
    disp(v)
end

Nested for loops

Put one for loop inside another to cover two dimensions. MathWorks’ example fills a 10-by-10 Hilbert matrix this way, with the outer loop on the row index and the inner loop on the column index. Each loop needs its own end.

How do I set up a while loop in MATLAB?

A while loop repeats its statements as long as an expression is true, and checks the expression at the start of each pass. The syntax is:

while expression
    statements
end

Because the check happens first, the body may never run if the expression is false at the start; MATLAB has no do…while form. MathWorks defines an expression as true when its result is nonempty and contains only nonzero elements (logical or real numeric), so for a matrix condition wrap it in any() or all() as you intend. The reference page also recommends the short-circuit operators && and || in loop conditions.

While loop example: factorial

This loop computes a factorial like the MathWorks example, which uses n = 10 and displays n! = 3628800.

n = 10;
f = n;
while n > 1
    n = n - 1;
    f = f*n;
end
disp(['n! = ' num2str(f)])

Two other examples on the page are a loop that reads a file line by line with while ~feof(fid), and an open-ended while 1 loop that uses break when a random number exceeds a limit.

How do I stop a loop in MATLAB?

There are two ways, depending on whether the stop is planned or not.

  • Planned stop from inside the code: use a break statement to exit the loop programmatically. Use continue to skip the rest of the current pass and begin the next iteration.
  • Emergency stop of a running loop: press Ctrl+C to stop execution of the loop. This is how you stop an infinite while loop. (Source: the MathWorks loop control statements page and the while page, checked 2026-11-07.)

Output and how to read it

A loop does not print anything by itself. What you see depends on what the body does: disp() or an unsuppressed assignment (no trailing semicolon) shows a value on every pass, while a semicolon suppresses the display. To keep results from a loop, assign into an indexed element such as result(k) = ... rather than overwriting one variable. For the 1.0:-0.2:0.0 range, the six index values listed above are what the body sees.

Troubleshooting

  • The loop ran once instead of once per element. You probably iterated over a column vector. Transpose it (x') so each value is a column.
  • The loop never stops. The while condition never becomes false. Press Ctrl+C, then check that something in the body changes the variables the condition tests.
  • The body never ran. A while expression is evaluated before the first pass, and it is only true if the result is nonempty and all nonzero. An empty or all-zero result skips the loop.
  • The index changed unexpectedly. MathWorks advises avoiding assigning a value to the index variable inside the loop statements, because for overrides it on the next pass.
  • The loop is slow because an array grows each pass. MathWorks notes that repeatedly resizing arrays often requires MATLAB to spend extra time looking for larger contiguous blocks of memory, and recommends preallocating the maximum space, for example x = zeros(1,1000000); before the loop (Preallocating arrays, checked 2026-11-07).

Free alternatives: the same loops in other tools

If you cannot use MATLAB, these free tools have equivalent constructs. Rows come from each project’s own documentation, checked 2026-11-07.

Tool For-type loop While-type loop Exit / skip How it iterates a matrix
MATLAB for index = values ... end while expression ... end break, continue One pass per column
GNU Octave for var = expression ... endfor Separate manual section Separate manual sections Assigns each column to the variable in turn, as in MATLAB
Python for w in words:, with range() for numbers while statement break, continue Iterates over the items of a sequence; range(10) gives 10 values starting at 0
R for(var in seq) expr while(cond) expr (also repeat) break, next Assigns each element of seq in turn

The practical difference when porting code: MATLAB and Octave loop over matrix columns (per their manuals above), Python’s range() starts at 0 and excludes its end point, and R uses next where MATLAB uses continue. For wider software choices see free statistical software for research, and for R specifically what R is used for and how to load data into R. Python users can continue with Python for exploratory data analysis. Scripted loops also support computational reproducibility, since the same script reruns the same steps.

FAQ

What are loops in MATLAB?

Loops are blocks of statements that repeat. MATLAB provides for loops, which run over a set of values, and while loops, which run while a condition is true. Both end with end.

How to set up a while loop in MATLAB?

Write while expression, the statements, then end. Make sure something in the body eventually makes the expression false, or use break.

What does the loop() function do?

MATLAB loops are written with the for and while keywords. See the syntax sections above.

How do I stop a loop in MATLAB?

Use break inside the loop for a planned exit, or press Ctrl+C to stop a running loop.

What is the difference between for and while in MATLAB?

A for loop is driven by a list of values and runs once per value or column. A while loop is driven by a condition checked at the start of each pass.

Sources (official documentation, checked 2026-11-07)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Loops in MATLAB: for, while and How to Stop Them

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →