| MATLAB® | ![]() |
| On this page… |
|---|
M-files often have a natural structure consisting of multiple sections. Especially for larger files, you typically focus efforts on a single section at a time, working with the code in just that section. Similarly, when conveying information about your M-files to others, often you describe the sections of the code. To facilitate these processes, use M-file cells, where cell means a section of code. Specifically, MATLAB® software uses cells for:
Rapid code iteration in the Editor — This makes the experimental phase of your work with M-file scripts easier. The next section, Rapid Code Iteration Overview, outlines the process, and is followed by details for defining, evaluating, and modifying values in cells.
Publishing M-files — This allows you to include code and results in a presentation format such as HTML. Publishing using cells also requires you to understand and define cells. You can make use of the cell navigation and evaluation features you specify for rapid code iteration or define and use cells explicitly for publishing. See Publishing M-Files for complete details.
When working with an M-file, you often experiment with your code—modifying it, testing it, and updating it—until you have an M-file that does what you want. Use the MATLAB Editor cell features with M-file scripts to facilitate this process. You can also use cell features with function M-files, but there are some restrictions—see Using Cells in Function M-Files.
If you have an active Internet connection, you can watch the Rapid Code Iteration Using Cells video demo for an overview of the major functionality.
This is the overall process of using cells for rapid code iteration:
In the MATLAB Editor, enable cell mode by selecting Cell > Enable Cell Mode. Items in the Cell menu become selectable. The cell toolbar appears, unless you had previously hidden it. With cell mode enabled, hide or show the toolbar by right-clicking in the Editor menu bar or toolbars and selecting Cell Toolbar from the context menu.
Define the boundaries of the cells in an M-file script using cell features. Cells are denoted by a specialized comment syntax, %%. For details, see Understanding and Defining Cells.
Once you define the cells, use cell features to navigate quickly from cell to cell in your file, evaluate the code in a cell in the base workspace, and view the results. To facilitate experimentation, use cell features to modify values in cells and then reevaluate them, to see how different values impact the result. For details, see Navigating and Evaluating with Cells.

A cell contains the contiguous lines of code that you want to evaluate as a whole in an M-file script. A cell has boundaries to define its start and end. Because cell features operate on cells, it is important to understand how you define boundaries explicitly, how MATLAB defines boundaries implicitly, and how implicitly and explicitly defined cell boundaries interact to create cells.
You define cell boundaries explicitly by inserting a line that begins with a cell break (also referred to as a cell divider), which is two percent sign characters (%%). White space can precede these two characters, and text can follow them, as long as there is white space between the %% characters and the text. For details on how you can insert a cell break, see Steps for Defining Cell Boundaries Explicitly.
MATLAB defines implicit cell boundaries in a code block only when you specify one or more explicit cell breaks within that code block. MATLAB defines implicit cell breaks as follows:
MATLAB defines implicit cell breaks at the top and bottom of the file, to create an implicit cell that contains the entire file. However, the Editor does not highlight the resulting cell, which encloses the entire file, unless you add one or more explicit cell breaks to the file.
If you define an explicit cell break in a function, MATLAB defines implicit cell breaks at the function declaration and at the function end statement.
The resulting cells are nested within the full file cell. Note that if you do not end the function with an explicit end statement, MATLAB behaves as though the end of the function occurs immediately before the start of the next function.
If you define an explicit cell break within a language construct (such as an if statement, a while statement, and so on), MATLAB defines implicit cell breaks at the lines containing the start and end of the language construct.
The resulting cells are nested within the full file cell, and the function in which the code block occurs, if any.
If an implicit cell break and an explicit cell break occur on the same line, they collapse into one explicit cell break. For more information on nested cells, see Understanding Nested Cells.
To define cell boundaries explicitly, follow these steps:
Ensure that cell mode is enabled. (See Rapid Code Iteration Overview.)
Optionally, to help you distinguish cells from each other, do one or both of the following:
To include a faint gray horizontal line (rule) above each cell to help you distinguish the cells from each other, select File > Preferences > Editor > Display, and then in Cell display options, select Show lines between cells.
The horizontal lines do not appear in the M-file when you print it.
To set a color to indicate the current cell select File > Preferences > Editor > Display. Then, in Cell display options, select Highlight cells, and then select the color that you want. By default, MATLAB highlights the current cell in yellow.
The current cell is the cell where you have placed the cursor. Like the lines between cells, highlighting helps you distinguish the cells from each other.
Do one of the following to insert the cell breaks:
Position the cursor just before the line at which you want to start the cell and select Cell > Insert Cell Divider .
Click the Insert Cell Divider button
.
Enter two percent signs (%%) at the start of the line where you want to begin the new cell.
Select the lines of code you want in a cell and then select Cell > Insert Cell Dividers Around Selection
You can define a cell at the start of a new empty file, enter code for the cell, define the start of the next cell, enter its code, and so on. Redefine cells by defining new cells, removing existing cell boundaries, and moving lines of code.
MATLAB does not execute the code in lines beginning with %%, so put any executable code for the cell on the following line. For program control statements, such as if ... end, a cell must contain both the opening and closing statements, that is, it must contain both the if and the end statements.
Note that MATLAB considers the entire file to be a single cell, therefore the first line in a file does not have to begin with %%.
After the %% characters, type a space, followed by a description of the cell. The Editor emphasizes the special meaning of the start of a cell by making any text following the percent signs appear bold. The text on the %% line is called the cell title. Including text in cell titles is optional, however, it improves the readability of the file and is used for cell publishing features.
When the cursor is positioned in any line within a cell, the Editor highlights the entire cell that contains that cell with a yellow background. This identifies it as the current cell. For example, it is used when you select the Evaluate Current Cell option on the Cell menu. If you do not want yellow highlighting for the current cell, change it using preferences. Select File > Preferences > Editor > Display and change the appropriate Cell display options.
This example defines two cells for a simple M-file called sine_wave.m, shown in the following code and figure.
The steps that follow insert a cell breaks into to the code to create two cells. The first cell creates the basic results, while the second labels the plot. The two cells allow you to experiment with the plot of the data first, and then when that is final, change the plot properties to affect the style of presentation.
% Define the range for x.
% Calculate and plot y = sin(x).
x = 0:1:6*pi;
y = sin(x);
plot(x,y)
title('Sine Wave','FontWeight','bold')
xlabel('x')
ylabel('sin(x)')
set(gca,'Color','w')
set(gcf, 'MenuBar', 'none')

Select Cell > Enable Cell Mode, if it is not already enabled.
Position the cursor at the start of the first line. Select Cell > Insert Cell Divider.
The Editor inserts %% as the first line and moves the rest of the file down one line. All lines are highlighted in yellow, indicating that the entire file is a single cell, assuming you have that display preference for cells selected.
After the %%, type a space and then enter a cell title.
%% Calculate and Plot Sine Wave
Position the cursor at the start of line 7, title..., and then select Cell > Insert Cell Divider.
The Editor inserts a line containing only %% at line 7 and moves the remaining lines down one line. A horizontal line that helps you distinguish the two cells appears above the %% line, assuming you have that display preference for cells selected. Lines 7 through 12 are highlighted in yellow, indicating they comprise the current cell.
On line 7, type a space after the %%, and then enter a cell title for the new cell.
%% Modify Plot Properties
Save the file. The file appears as shown in this figure.

To remove a cell, do one of the following:
Delete one of the percent signs (%) from the line that starts the cell.
This changes the line from a cell break to a standard comment.
Delete the entire line that contains the %% characters.
In both cases, because you remove the cell break, MATLAB merges the two cells that were previously separated by the cell break.
You can insert cells within nested code, which results in nested cells. The following sections illustrate how inserting explicit cell breaks interacts with the implicit cell breaks that MATLAB inserts within an M-file.
The following code when viewed in an M-file displays no cells or highlighting; it is a single, implicit cell, defined by MATLAB.
function fourier
t = 0:.1:pi*4;
y = sin(t);
updatePlot(1,t,y);
for k = 3:2:9
y = y + sin(k*t)/k;
display(sprintf('When k = %.1f',k));
end
end
function updatePlot(k,t,x)
cla
plot(t,x)
endThis code appears as shown in the following image when you view it in the Editor.

Suppose you insert two cell breaks into fourier.m as follows:
One within the fourier function, at line 5.
One within the for loop, at line 7.
This results in the following cells, which are illustrated in Example M-File With Nested Cell Breaks:
One at the outermost level, from the top to the bottom of the file.
Two at the second level, within the fourier function:
One from the implicit break at line 2 to the explicit break at line 5.
One from the explicit break at line 5 to the implicit break before line 11 (end of the function).
One at the third level, within the for loop from the explicit line break at line 7 to the implicit line break before line 10.
The following images illustrate how inserting explicit cell breaks as described in How Nesting Cell Breaks Result in Cells affect the appearance of the M-file:
First level of nesting — When you place the cursor outside a function, at the outermost level, the entire file is highlighted showing that it comprises a cell at this level of nesting.

MATLAB only defines implicit cell breaks in a code block if you specify an explicit cell break within that code block. Therefore, because function updatePlot in this example has no explicit (and therefore, no implicit) cell breaks defined for it, when you place the cursor within that function, MATLAB considers the cursor to be within the cell that encloses the whole file.

Second level of nesting — When you place the cursor within the function (but outside the for loop), either the first or second cell at this level of nesting is highlighted, depending on where the cursor is located.


Third level of nesting — When you place the cursor within the for loop, the cell within this loop is highlighted.

Be aware that if you want a cell break to be associated with a subfunction, you should place it within the subfunction, rather than above the subfunction declaration. Otherwise, it creates a single cell within the code block that precedes the subfunction. The following two images demonstrate this using collatzplot_new.m.


While you develop an M-file, you can use these Editor cell features:
To move to the next cell, select Cell > Next Cell. To move to the
previous cell, select Cell > Previous Cell. To move to
a specific cell, click the Show Cell Titles button
and from
it, select the cell title to which you want to move. You can also
go to cells by selecting Edit > Go To.
To evaluate the code in a cell, use the Cell menu evaluation items or equivalent buttons in the cell toolbar. When you evaluate a cell, the results display in the Command Window, figure window, or otherwise, depending on the code evaluated.
The cell evaluation features run the code currently shown in the Editor, even if the file contains unsaved changes. The file does not have to be on the search path. To evaluate a cell, it must contain all the values it requires, or the values must already exist in the MATLAB workspace.
Evaluate Current Cell.
Select Cell > Evaluate Current Cell or click the Evaluate Cell button
to run the
code in the current cell.
Evaluate and Advance.
Select Cell > Evaluate Current Cell
and Advance or click the Evaluate Cell
and Advance button
to run the code in the
current cell and move to the next cell.
Evaluate File.
Select Cell > Evaluate Entire File or click the Evaluate Entire File button
to run all
of the code in the file. By default, the Evaluate Entire File button
is not on the Editor toolbar. See Toolbars Preferences for the MATLAB® Desktop and Editor for information on how to add it.
Note A beep means there is an error. See the Command Window for the error message. |
This section describes processing considerations that you need to take into account when you evaluate cells in M-files.
Setting Breakpoints. While you can set breakpoints and debug a file containing cells, when you evaluate a file from the Cell menu or cell toolbar, breakpoints are ignored. To run the file and stop at breakpoints, use Run/Continue in the Debug menu. This means you cannot debug while running a single cell.
Using Cells in Function M-Files. You can define and evaluate cells in function M-files as long as the variables referenced in the cell are in your workspace. This can be useful during debugging. If execution is stopped at a breakpoint, you can define cells and execute them without saving the file. If you are not debugging, add the necessary variables to the base workspace and then execute the cells.
Using Function Names as Variable Names in Cells. If you use a MATLAB function name as a variable name within a cell, you may receive an unexpected error when you evaluate the cell. The precedence rules that MATLAB typically follows do not apply when it evaluates a cell. Typically, MATLAB evaluates variables before functions. However, when you evaluate cells, MATLAB parses all the cell code and loads it into memory before evaluating it. Therefore, functions might be evaluated before variables under some circumstances, as illustrated by the following example:
Suppose you create a MAT file, mydata.mat, using the following commands:
clear all info=5; save mydata.mat clear all
When you enter the following commands in the Command Window, b evaluates to 5, as expected:
load mydata b=info
However, when you evaluate the same commands in an M-File cell, b evaluates to the MATLAB info function, thus the Command Window displays the following error:
??? Error using ==> info Too many output arguments.
For this reason, you may want to avoid using function names as variable names within M-file cells.
You can use cell features to modify numbers in a cell, which also automatically reevaluates the cell. This helps you experiment with and fine-tune your code.
To modify a number in a cell, select the number (or place the cursor near it) and use the value modification tool in the cell toolbar. Using this tool, you can specify a number and press the appropriate math operator to add (increment), subtract (decrement), multiply, or divide the number. The cell then automatically reevaluates.

You can use the numeric keypad operator keys (-, +, /, and *) instead of the operator buttons on the toolbar.
Note MATLAB software does not automatically save changes you make to values using the cell toolbar. To save changes, select File > Save. |
In this example, modify the values for x in sine_wave.m:
Run the first cell in sine_wav.m. Click somewhere in the first cell, that is, between lines 1 and 6. Select Cell > Evaluate Current Cell. The following figure appears.

Assume you want to produce
a smoother curve. Use more values for x in 0:1:6*pi. Position the cursor in line 4, next to the 1. In the cell toolbar, change the 1.1 default multiply/divide by value to 2. Click
the Divide button
.
Line 4 becomes
![]()
and the length of x doubles. The plot automatically updates. The curve still has some rough edges.
To add more values for x, click the Divide button three more times. Line 4 becomes
![]()
The curve is smooth, but because there are more values, processing time is slower. It would be better to find a smaller x that still produces a smooth curve.
In the cell toolbar, click the Multiply button once. The increment for x as shown in line 4 changes from 0.0625 to 0.125.
The resulting curve is still smooth.
Now you can apply the plot properties, defined in the second cell, that is, lines 7 through 12. You do not need to evaluate the entire file to apply the plot properties. Instead, position the cursor in the second cell and use the shortcut Ctrl+Enter to evaluate the current cell. (The shortcut appears with the menu item, Cell > Evaluate Current Cell.)
MATLAB updates the figure.

![]() | Debugging Process and Features | Tuning and Managing M-Files | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |