| Products & Services | Industries | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about 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 refers to a section of code. 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, as described in Defining Cells
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 define cells. You can make use of the cell navigation and evaluation 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. For example:
Suppose you have code that plots data. You might break the code into two cells: the code in the first cell creates the basic results, while the code in the second cell 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. This scenario is presented in Example of Evaluating Cells.
Suppose you have an two images that you want to add together, and then display the results. As part of this algorithm, you want to adjust the brightness of the second image before adding it to the first image. You can read in that images, tweak the second image's brightness, read it in again, adjust its brightness, and so on using the cell mode toolbar buttons until you see the brightness you want. There is no need to save the M-file between adjustments. If you have an active Internet connection, you can watch the Rapid Code Iteration Using Cells video demo that illustrates this example and more, including an overview of the major rapid code iteration features.
Use the MATLAB Editor cell features with M-file scripts to facilitate this process. You also can use cell features with function M-files, but there are some restrictions—see Using Cells in Function M-Files.
Note Cell mode is supported for use with M-files only. It is not intended for use with plain text files. When used with plain text files, results are unpredictable. |
This is the overall process of using cells for rapid code iteration:
In the MATLAB Editor, select 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 Defining Cells.
After 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 Evaluating M-File 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, see 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.
This section includes the following topics:
To define cell boundaries explicitly, you must insert cell breaks. 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:
Include a faint gray horizontal line (rule) above each cell to help you distinguish the cells from each other.
Select File > Preferences > Editor/Debugger > 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.
Set a color to indicate the current cell.
Select File > Preferences > Editor/Debugger > 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 Break .
Click the Insert cell break 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 Breaks Around Selection
Note Program control statements, such as if ... end, must be contained within a single cell. You cannot insert a cell break between the if and the end statements. |
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.
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.
To create a cell title, after the %% characters that specify a cell break, type a space, followed by a description of the cell.
When the cursor is positioned in any line within a cell, the Editor highlights the entire cell that contains that line with a yellow background, by default. This identifies it as the current cell. For example, it is used when you select the Evaluate Current Cell option on the Cell menu.
Turning Off Cell Highlighting.
Select File > Preferences > Editor/Debugger > Display.
UnderCell display options, deselect Highlight cells.
Setting a Color for Cell Highlighting.
Select File > Preferences > Editor/Debugger > Display.
Under Cell display options, select Highlight cells.
Click the down arrow next to the color block beside Highlight cells, and then select the color with which you want to highlight cells.
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 the code to create two cells. The code in 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 Break.
The Editor inserts %% as the first line and moves the rest of the file down one line. All lines appear 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 Break.
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 appear 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.

If you introduce an error into a file, such as a syntax error, cell highlighting and dividers may not appear as you expect. Although dividers and highlighting for existing cells remain in place, cells you insert after you have introduced the syntax error do not appear highlighted. In addition, if you close and reopen the file, then all cell dividers are gone and none of the cells appears highlighted.
For example, suppose your code currently appears as specified in the Example of Defining Cells, and as shown here.

If you accidentally insert a syntax error (a closing bracket at the end of line 6), the error is evident by the M-Lint marker. The cell highlighting remains as-is.

However, if you attempt to introduce a new cell at line 7, a cell divider does not appear above line 7 and the highlighting does not indicate a new cell, as you might expect.

In addition, if you save, close, and then reopen the file, all cell dividers and highlighting are gone.

To fix the problem, correct the syntax error. The cell dividers and highlighting reappear.

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.
The following list summarizes facts to keep in mind when using cell mode and defining cells:
Cell mode is supported for use with M-files only. It is not intended for use with plain text files.
MATLAB does not execute the code in lines beginning with cell break characters, %%.
MATLAB considers the entire file to be a single cell; therefore, the first line in a file does not have to begin with %%.
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.
You can set preferences for cell display options by selecting File > Preferences > Editor/Debugger > Display, and then making choices for Cell Display options.
If M-Lint finds errors in a file, cell dividers and highlighting may not appear as you expect. For details, see Fixing Cell Highlighting Problems.
For more information on M-Lint, see Checking M-File Code for Problems Using the M-Lint Code Analyzer.
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 cell at the outermost level, from the top to the bottom of the file.
Two cells 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 cell 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 inHow 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 appears 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 appears 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.


As you develop an M-file, you can use the Editor cell features to evaluate the M-File cell-by-cell. This method helps you to experiment with, debug, and fine-tune your code. You can navigate from cell to cell, and evaluate each cell individually. See the following topics for details:
| Operation | Instructions |
|---|---|
| Move to the next cell. | Select Cell > Next Cell. |
| Move to previous cell. | Select Cell > Previous Cell. |
| Move to a specific cell. | Do either of the following:
|
The cell evaluation features run the cell 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 exist in the MATLAB workspace.
To run the code in a cell, use the Cell menu evaluation items or equivalent buttons in the cell mode toolbar. When you evaluate a cell, the results display in the Command Window, figure window, or elsewhere, depending on the code evaluated.
| Operation | Instructions |
|---|---|
| Run the code in the current cell. | Select Cell > Evaluate
Current Cell or click the Evaluate cell
button
|
| Run the code in the current cell, and then move to the next cell. | Select Cell > Evaluate
Current Cell and Advance or click the Evaluate
cell and advance button
|
| Run all the code in the file. | Select Cell > Evaluate
Entire File or click the Evaluate entire
file button
By default, the Evaluate entire file button is not on the Editor toolbar. See Setting Toolbars Preferences for Desktop Tools for information on how to add it. |
This section describes processing considerations that you should 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 might 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 choose Cell > Evaluate Current Cell to evaluate the current cell.
MATLAB updates the figure.

![]() | Debugging Process and Features | Debugging Functions | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |