Scripts and Cells

A number of students have had questions regarding how scripts work and why we have been using cell formatting to complete Assignment 1. While it is not necessary to completely understand these concepts to complete Assignment 1, I thought I would clarify a few points here.

Contents

As I explain later, it is often a good idea to clear the variables in your workspace at the beginning of a script.

clear;

Script files

A script is a file with a .m extension that contains MATLAB commands. For example, I have a script file called JustAScript.m.

type JustAScript.m
% This is a normal MATLAB script that contains no cell formatting.

% Compute powers of two
x = 0:16;
y = 2.^x;

% Display vectors side-by-side 
[x' y']

To instruct MATLAB to evaluate all of the commands in the script, type the name of the script in the Command Window

JustAScript
ans =

           0           1
           1           2
           2           4
           3           8
           4          16
           5          32
           6          64
           7         128
           8         256
           9         512
          10        1024
          11        2048
          12        4096
          13        8192
          14       16384
          15       32768
          16       65536

Executing a script has the same effect as typing each line of the script into the Command Window. The obvious advantage is that if you want to perform a lot of actions more than once, it is more convenient to instruct MATLAB to execute a script than it is to manually type commands over and over again.

You can also execute a script by clicking on the "Save and Run" button on the toolbar of the MATLAB Editor.

You may want to issue a clear command as the first command in your script files. This will clear all variables from your MATLAB workspace before executing the rest of your script. This ensures you are starting from a clean MATLAB environment, and that your script does not depend on previously-defined variables or expressions entered previously in the Command Window.

Similarly, the close command will close all figure windows.

Current Directory

MATLAB can only execute user-written scripts if they are in MATLAB's Current Directory. (There is a way to add directories to MATLAB's search path, but I do not suggest doing this quite yet.) The Current Directory bar on the main toolbar shows you which directory is current. The Current Directory panel--on the right in the default desktop layout--shows the contents of the Current Directory. The commands pwd, dir, and cd shows the name of the Current Directory, shows the contents of the Current Directory, and lets you change the Current Directory, respectively. For example, my Current Directory contains:

dir
.                          FigureExample.m~           
..                         JustAScript.m              
AScriptWithCells.m         ScriptsAndCells.m          
CellEditingScreenshot.png  ScriptsAndCells.m~         
CellFormat.m               html                       
FigureExample.m            

Comments

In addition to MATLAB commands, a script can contain comments, which are preceded by the '%' character. JustAScript.m contains several comments. Comments in scripts are not evaluated by MATLAB.

There are multiple benefits to commenting:

Good programming practice dictates commenting code liberally.

Workspace

What do I mean when I say, "executing a script has the same effect as typing each line of the script into the Command Window?"

If you type an expression like

z = 10;

into the Command Window, you have created a variable named x with the value 10 assigned to it. MATLAB keeps track of variables in a "workspace." You can see the contents of the MATLAB workspace in the Workspace panel or by using the command whos.

whos
  Name       Size            Bytes  Class     Attributes

  ans       17x2               272  double              
  x          1x17              136  double              
  y          1x17              136  double              
  z          1x1                 8  double              

Notice that we have three variables defined. x and y were created when we ran JustAScript.m.

So, if you type an assignment expression in the Command Window, the variable gets added to the workspace. And any time you run a script, the variables created within the script are also added to the workspace.

Cells

You can add simple formatting to a script file to get a little more functionality out of it within MATLAB. Cells let you break a script file up into smaller logical units. To create a new cell, start a new line with two percent signs, '%% '. Note that there is a space after the percent signs.

Cells in a script file are separated by horizontal lines in the MATLAB Editor. The cell in which the cursor is placed is highlighed in yellow.

Here is a picture of my editor, where the cursor is in the cell I am currently editing.

For example the sample script from above could be marked up using the cell formatting.

type AScriptWithCells.m
%%
% This is a MATLAB script that uses cell formatting.

%%
% Compute powers of two
x = 0:16;
y = 2.^x;

%%
% Display vectors side-by-side 
[x' y']

Note that marking up a script file with cells does not change how that script is executed by MATLAB. We get exactly the same result when we execute the new script. What changes is how the script file is displayed in the Editor.

AScriptWithCells
ans =

           0           1
           1           2
           2           4
           3           8
           4          16
           5          32
           6          64
           7         128
           8         256
           9         512
          10        1024
          11        2048
          12        4096
          13        8192
          14       16384
          15       32768
          16       65536

One useful feature of marking a script file up with cells is that now you can instruct MATLAB to execute the code within the currently selected cell by pressing Ctrl-Enter or selecting Cell > Evaluate Current Cell from the Cell menu in the Editor window. This is useful when developing scripts. You can break the problem you are working on into logical blocks, and work on each block in isolation. While you are working on the code for a logical block, you can instruct MATLAB to execute that cell without evaluating your entire script.

Publishing

Another feature you gain by formatting your scripts with cells is that MATLAB can generate well-formatted documents for you from your scripts. This is what we do in Assignment 1. For publishing purposes, the general formatting guidelines MATLAB uses are outlined in the script file below.

type CellFormat.m
%% Document Title
% Document introduction

%% Cell title
% Formatted text
%
% Another paragraph of formatted text

% code comment
help publish;

%%
% A cell without a title

% Another code comment.

To publish a script file as HTML, select File > Save and Publish To > HTML from the Editor window menu. Alternatively, type the following in the Command Window:

publish CellFormat.m;

The published output that MATLAB generates from this simple script can be viewed here.

In the published document, each cell receives a title (optional), formatted text block, code block, and results block. The whole document also gets a title and a linked table of contents to cells with titles.

The cell editing and publish feature of MATLAB makes it easy to create well-documented, complete reports. The alternative would be to create a Word/OpenOffice document that includes MATLAB code and figures copied from figure windows.

Spaces matter! When you are setting up a new cell, the double percent ('%%') signs should be followed by a space (or new line) before any other text. Otherwise, MATLAB will not recognize this as a new cell.

Important: Do not try to publish your script from a command within your script file. When MATLAB publishes a script, it executes the code within. If MATLAB finds a command to publish your script while doing this, it will start publishing your script again...and again...and again...forever. Or at least until MATLAB runs out of memory or realizes it's stuck in an infinite loop.

Figures

A script file may display information (images, graphs, etc) in figure windows. MATLAB includes these figures in your published document. The very important caveat, however, is that only one figure per cell is displayed. To display multiple figures, make sure each figure display function, (e.g. imagesc, plot, surf, etc.) resides in a different cell.

As we learn to annotate and enhance figures--with labels, multiple plots, subfigures, etc.--remember to include these commands in the same cell in which the figure was created.

The script FigureExample.m demonstrates this.

type FigureExample.m
publish FigureExample.m;
%% Figure Example
% Demonstrates creating figures in MATLAB for publishing.

%% Sinc
% Here we show how to create a plot and label the figure.

% Plot a sinc
x = 0:0.2:4*pi;
plot(x, sin(2*x)./x);
title('sin(2x)/x');

%%
% Note that the published plot includes the title. MATLAB publishes the
% figure as it appears at the end of the cell.

%% Cos and Bessel
% Here we show what happens when we create more than one figure in a cell.

% Plot a cos
plot(x, cos(x));
title('cos(x)');

% Plot Bessel functions
plot(x, besselj(0:4,x'));

%%
% Note that in the published version, only the figure that results from the
% second plot appears.

The published version of this script is here.

Guidelines

The following are tips I would suggest for students to follow when formatting their script files for publishing in this class.

The first cell in your script file should have no code. The text in the first cell title position will become the title of your document. Comments that are connected to the cell title (no blank lines) will become formatted introductory text. This is a good place to put your name and a brief description of the assignment.

Include in your reports an explanation of how you answered each question in plain English; this should be a few sentences for each question. You should not be explaining every line of code, but rather providing a conceptual description of what you are doing. When you do this following the formatting in the CellFormat.m example above, each cell will get a section title and formatted descriptive text. The cell titles from the script will be included in a linked table of contents at the beginning of the report.

A cell without a title will not be included in the table of contents, but will still have a formatted text, code, and result section in the body of the report.

You can include simple markup tags in the formatted text portion of each cell to create bold, italicized, or other text styles. See the Cell > Insert Text Markup menu on the Editor window for some options.

More information

More information on publishing in MATLAB can be found in the Help browser under MATLAB > Desktop Tools > Publishing Results. Also, try doc publish. Yet more information is here.

About

This document was created using the cell editing feature of MATLAB. I will post this document on Blackboard as a zip archive. This is an example of how you should be turning in your assignments.

I suggest that you create a new directory on your computer for each assignment. When you have completed the assignment and published your document, archive the assignment folder. The archive will contain your MATLAB script(s), data files, and the generated HTML directory.

In other words, the archive you turn in should contain everything you used to complete the assignment. That means I can extract the archive to my machine, change the MATLAB Current Directory, and have exactly the same environment you used when you completed your assignment.

Brian Eastwood
Comp 116
1/16/2008