Skip to Main Content Skip to Search
Product Documentation

Evaluate Subsections of Files Using Code Cells

What Are Code Cells?

MATLAB files often have a natural structure consisting of multiple sections. In large 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 files to others, often you describe the sections of the code. To facilitate these processes, use code cells. A code cell contains the contiguous lines of code that you want to evaluate as a whole in a MATLAB script. A code cell has boundaries to define its start and end. Because code cell features operate on code cells, it is important to understand how you define boundaries explicitly, how MATLAB defines boundaries implicitly, and how implicitly and explicitly defined code cell boundaries interact to create code cells, as described in Define Code Cells

Specifically, MATLAB software uses code cells for:

MATLAB Code Cells in Files

Denote MATLAB code cells with two comment characters (%%) at the start of a line and save the file using .m as the extension. If you open a file that contains MATLAB code cells when cell mode is enabled, then highlighting and horizontal lines appear in the file.

If you do not want cell mode enabled, select Cell > Disable Cell Mode.

The first time you open a file that contains cells, an information bar appears below the cell toolbar, providing links for details about cell mode.

Scenarios for Evaluating Sections of Code

When working with a MATLAB file, you often experiment with your code—modifying it, testing it, and updating it—until you have a file that does what you want. For example:

Use the MATLAB code cell features with MATLAB scripts to facilitate this process. You also can use code cell features with MATLAB function files, but there are some restrictions—see Code Cells in MATLAB Function Files.

Process for Evaluating Sections of Files

This is the overall process of using code cells to evaluate sections of code:

  1. In the MATLAB Editor, select Cell > Enable Cell Mode.

  2. Define the boundaries of the cells in a MATLAB script using cell features. Code cells are denoted by a specialized comment syntax, %%. For details, see Define Code Cells.

  3. After you define the code cells, use cell features. Cell features enable you 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 affect the result. For details, see Evaluate Code Cells.

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

Define Code Cells

You define code 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, if there is white space between the %% characters and the text. For details, see Define Code 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 Nested Code Cells.

This section includes the following topics:

Define Code Cell Boundaries Explicitly

To define code cell boundaries explicitly, insert cell breaks:

  1. Select Cell > Enable Cell Mode.

  2. Do one of the following to insert 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.

If cell breaks do not appear in your Editor document, check preferences for Cell display options by selecting File > Preferences > Colors > Programming Tools.

Create Titles for Code 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.

Highlight Code 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. The current cell is used, for example, when you select the Evaluate Current Cell option from the Cell menu.

Turn Off Code Cell Highlighting.  

  1. Select File > Preferences > Colors > Programming Tools.

  2. Under Cell display options, clear Highlight cells.

Set a Color for Code Cell Highlighting.  

  1. Select File > Preferences > Colors > Programming Tools.

  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 Code Cells

This example defines two cells for a file called sine_wave.m, shown in the figure that follows. To open this code in your Editor, run the following command and then save the file to a local folder:

edit(fullfile(matlabroot,'help','techdoc',...
'matlab_env','examples','sine_wave.m'))

The steps that follow insert a cell break 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 enable 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.

  1. Select Cell > Enable Cell Mode.

    When cell mode is enabled, the Cell menu displays Disable Cell Mode.

  2. Select File > Preferences > Colors > Programming Tools, and then select Highlight cells and Show lines between cells.

  3. Position the cursor at the start of the first line. Select Cell > Insert Cell Break.

    The Editor inserts a cell break %% 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 that you have that display preference for cells selected.

  4. After the cell break, type a space, and then enter a cell title.

     %% Calculate and Plot Sine Wave
    
  5. Position the cursor at the start of line 7, title..., and then select Cell > Insert Cell Break.

    The Editor inserts a line containing only a cell break (%%) at line 7 and moves the remaining lines down one line. A horizontal line that helps you distinguish the two cells appears above the cell break line. Lines 7 through 12 appear highlighted in yellow, indicating they comprise the current cell.

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

Fix Code Cell Highlighting Problems

If you introduce an error into a file, such as a syntax error, cell highlighting and dividers might 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 Code Cells. Make sure that automatic code analysis is enabled by selecting File > Preferences > Code Analyzer, and then selecting Enable integrated warning and error messages.

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

However, if you attempt to introduce a new cell at line 7, an extra cell divider line appears between lines 5 and 6.

To fix the problem, correct the syntax error. The extraneous cell divider disappears.

Remove Code Cells

To remove a code 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 Code Cell Requirements

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

For more information, see Avoid Mistakes While Editing Code.

Nested Code 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 a file:

File Without Explicit Code Cell Breaks

The following code when viewed in the Editor displays no cells or highlighting. It is a single, implicit code 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

To follow this example, save the code to a local folder with the file name fourier.m.

How Nesting Code 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 8

This results in the following cells, which are illustrated in Example File with Nested Code Cell Breaks:

Example File with Nested Code Cell Breaks

The following images illustrate how inserting explicit cell breaks, as described in How Nesting Code Cell Breaks Result in Cells, affect the appearance of the file:

Associate Code Cell Breaks with Subfunctions

If you want a cell break to be associated with a subfunction, place the cell break within the subfunction, rather than above the subfunction declaration. Otherwise, the cell break creates a single cell within the code block that precedes the subfunction. The following two images demonstrate the difference.

Navigate Among Code Cells in a File

You can navigate among cells in a file without evaluating the code within those cells, as described in the table that follows. This can be useful when you want to jump quickly from cell to cell within a file. You might do this, for example, to find the point at which you want to begin cell evaluation. By default, the cell mode navigation buttons are not on the Editor Cell Mode toolbar. For information on how to add them, see Toolbar Customization.

OperationInstructions
Move to the next cell.Select Cell > Next Cell or click the Next Cell button .
Move to the previous cell.Select Cell > Previous Cell or click the Previous Cell button .
Move to a specific cell.

Do either of the following:

  • Use the Editor Cell Mode toolbar:

    1. Click the Show cell titles button .

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

  • Use the Go menu:

    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.

Evaluate Code Cells

As you develop a MATLAB file, you can use the Editor cell features to evaluate the 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:

Evaluate Code Cells in a 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.

The following table provides instructions on evaluating code cells.

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 Cell Mode toolbar. See Toolbar Customization 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 Code Cells

This section describes processing considerations to take into account when you evaluate code cells in MATLAB files.

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

Code Cells in MATLAB Function Files.  You can define and evaluate cells in MATLAB function files as long as the variables referenced in the code 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.

Modify Values in a Code Cell

You can use code cell features to modify numbers in a cell, which also automatically reevaluates the cell. This helps you experiment with and fine-tunes 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 Code 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 that 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 select 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-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS