Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

Using Cells for Rapid Code Iteration and Publishing Results

What Are Cells?

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 Overview

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:

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.

This is the overall process of using cells for rapid code iteration:

  1. 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.

  2. 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.

  3. 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.

Image of Editor showing Cell menu and cell toolbar. The current cell is highlighted (in yellow).

Defining 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:

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:

Defining Cell Boundaries Explicitly

To define cell boundaries explicitly, you must insert cell breaks. Follow these steps:

  1. Ensure that cell mode is enabled. (See Rapid Code Iteration Overview.)

  2. 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.

  3. 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

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.

Creating Titles for Cells

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.

Highlighting Cells

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.  

  1. Select File > Preferences > Editor/Debugger > Display.

  2. UnderCell display options, deselect Highlight cells.

Setting a Color for Cell Highlighting.  

  1. Select File > Preferences > Editor/Debugger > Display.

  2. Under Cell display options, select Highlight cells.

  3. Click the down arrow next to the color block beside Highlight cells, and then select the color with which you want to highlight cells.

Example of Defining 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')

Image of file sine_wave.m in Editor before defining cells.

  1. Select Cell > Enable Cell Mode, if it is not already enabled.

  2. 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.

  3. After the %%, type a space, and then enter a cell title.

     %% Calculate and Plot Sine Wave
    
  4. 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.

  5. 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.

Image of sine_wave.m file in Editor after defining cells. Each cell begins with %% followed by an associated title.

Fixing Cell Highlighting Problems

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.

Removing Cells

To remove a cell, do one of the following:

In both cases, because you remove the cell break, MATLAB merges the two cells that were previously separated by the cell break.

Summary of Cell Mode and Cell Requirements

The following list summarizes facts to keep in mind when using cell mode and defining cells:

For more information on M-Lint, see Checking M-File Code for Problems Using the M-Lint Code Analyzer.

Understanding Nested Cells

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.

M-File Without Explicit Cell Breaks

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)
    
end

This code appears as shown in the following image when you view it in the Editor.

Image of Editor with file open in it and no cell breaks visible within it.

How Nesting Cell Breaks Result in Cells

Suppose you insert two cell breaks into fourier.m as follows:

  1. One within the fourier function, at line 5.

  2. 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:

Example M-File with Nested Cell Breaks

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:

Associating Cell Breaks with Subfunctions

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.

Evaluating M-File Cells

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:

Navigating Among Cells in an M-File

OperationInstructions
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:
  • Use the Editor Cell Mode toolbar, as follows:

    1. Click the Show cell titles button .

    2. Select the cell title to which you want to move.

  • Use the Go menu, as follows:

    1. Select Go > Go To.

      The Go To dialog box opens.

    2. Select Function or cell title.

    3. Select the cell title to which you want to move.

    4. Click OK.

Evaluating Cells in an M-File

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.

OperationInstructions
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.

    Note   A beep indicates there is an error. See the Command Window for the error message.

Processing Considerations When Evaluating Cells

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.

Modifying Values in a Cell

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.

Image of increment/decrement and divisor/multiplier buttons and numbers on cell toolbar.

You can use the numeric keypad operator keys (-, +, /, and *) instead of the operator buttons on the toolbar.

Example of Evaluating Cells

In this example, modify the values for x in sine_wave.m:

  1. 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.

    Image of plot showing the results of running sine_wave.m. The plot is not smooth.

  2. 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 Button with Tooltip .

    Line 4 becomes

    Image of line 4, showing x = 0:0.5:6*pi.

    and the length of x doubles. The plot automatically updates. The curve still has some rough edges.

  3. To add more values for x, click the Divide button three more times. Line 4 becomes

    Image of line 4, showing x = 0:0625.5:6*pi.

    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.

  4. 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.

  5. Save these changes. Select File > Save.

  6. 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.

    Image of plot of sine_wave.m, showing a smoother curve.

  


Recommended Products

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