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 means a section of code. 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. 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:

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

  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 Understanding and Defining Cells.

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

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

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

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.

Steps for Defining Cell Boundaries Explicitly

To define cell boundaries explicitly, 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:

  3. Do one of the following to insert the cell breaks:

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

Cell Titles and Highlighting

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.

Example — Define 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 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')

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

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

  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.

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.

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 in How 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.

Navigating and Evaluating with Cells

While you develop an M-file, you can use these Editor cell features:

Navigating Among Cells in an M-File

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.

Evaluating Cells in an M-File

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.

Processing Considerations When Evaluating Cells

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.

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 — Evaluate 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 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.

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

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS