MATLAB Style Guide

[under construction]

Written by David I. Schwartz, Fall 2002. Some portions are adapted from previous CS99 and CS100 style guides from Fall 1998-Summer 2001 and Chapman's MATLAB textbook.


Table of Contents
 
0. Notation
1. Introduction
2. General Principles
3. Documentation
    3.1 Internal Documentation: Comments
    3.2 External Documentation: User Manual
4. Title Block
    4.1 Name
    4.2 Purpose
    4.3 Authorship
    4.4 Revision Record
    4.5 Copyright?
5. Statements
    5.1 Rules and Guidelines
    5.2 Punctuation
6. Variables
    Naming
    Describing
    Named Constants
    Global vs Local
    Predefined Values
7. Expressions
    Spacing
    Parentheses
    Variables
    Operators
8. Arrays
Arrays and Matrices
Notation
Punctuation
Operators
9. Indentation
    Substructures
    Statement Comments
    Selection Statements (if, elseif, else)
    Repetition Statements (while, for)
10. Functions
    Naming
    Modularizing
    Preconditions
    Postconditions
    H1 Line
    Help Lines
    Indentation
    Body
11. Plots
    Title
    Axis Labels
    Legend
    Subplots
12. Toolboxes
13. MATLAB Memory
    Preallocation
    Vectorizing
14. Help Files
15. Miscellaneous?
16. Glossary
 
 
 
 
 

 

Top
0. Notation

This guide uses the following notation:

Top
1. Introduction

Many programmers disagree on the "right" programming style, which incorporates these two styles:

When learning how to program, not only do you need to learn how to write correct code, but you need to write clear code that will serve the following purposes: Ultimately, you will develop your own "writing style," but until you do, you should strongly consider the advice that this guide contains. You should also consult with MATLAB > Using MATLAB > Programming and Data Types > M-File Programming,  You will look here for most help pages for this document.
Top

2. General Principles

This portion lists general principles, or "rules of thumb," that you should consider when writing your code, especially if you develop your style. Many legions of programmers generally agree that you will produce clear code if you adhere to the following principles:

Top

3. Documentation

Documentation consistents of two types:

3.1 Internal Documentation

Internal documents are comments, which are inert elements of text that most compilers ignore. In MATLAB, you start a comment with a percent sign (%):

For more information, go to MATLAB's programming guide (see Section 1) and scroll to the bottom of Functions > Basic Parts of a Function M-File.

3.2 External Documentation

A program or package typically includes a user manual, which is a document that  teaches a person how to use your program. For instance, click on the ? icon in the MATLAB interface to pull up the MATLAB Help Desk. Entire careers, such as technical writing, are devoted to the art of writing a user manual. Typically, the user manual is written apart from the software, though sometimes you may supply special kinds of comments that help to provide this documentation. For instance, inside MATLAB function M-Files, you may supply comments that MATLAB's help and lookfor functions will find when a user looks for help on your function.
Top


4. Title Block

As you write a title page of an essay or article, you need to title your program with a title block, which is a collection of comments that identify and describe your program at the top of the file. For CS99 and CS100, you have specific guidelines for each assignment. This section discusses the general elements of a title block.

4.1 Name

Choose a name for your program that has some, or all, of the following features, depending on the specifications of the project:

Write the name at the top of the program.

4.2 Purpose

Briefly explain what the program does. If the program contains modules/functions/methods/classes, you should also briefly list and explain the purpose of these contents.

4.3 Authorship

List the authors that contributed to the writing of the program. You might need to write the authors' job titles along with their names. Sometimes programmers write the date that they started or finished the work next to their names. You may prefer to use a formal description called a revision record, especially if you have multiple authors making many changes, as described in Section 4.4.

4.4 Revision Record

Chapman demonstrates excellent examples of a revision record, which records the date, authorship, and contributions/changes that each programmer has made to the program. See page 51, for example.

4.5 Copyright

[future topic]

Top



5. Statements

Statements are essentially individual instructions to the computer. Think of a statement as a sentence that is composed of words and punctuation. As you would write a paragraph, you need a consistent way to write statements in a logical and syntactical order.

5.1 Rules and Guidelines

The following rules summarize common syntax and style:

5.2 Punctuation

MATLAB provides different kinds of punctuation that affect when and how MATLAB ends statements:

Refer to help punct for a brief overview of these and other forms of MATLAB punctuation.
Top
6. Variables

Variables assist programmers in clarifying their code by storing values and expressions. Older languages restricted variable names with constraints in length and lack of case sensitivity. Although you will occasionally confront these irritations, most "modern" languages have abandoned these antiquated notions in favor of flexible variable syntax. This section discusses some of the general syntax that will encounter but focuses on the style conventions.

6.1 Naming

When choosing variable names, follow this advice:

6.2 Describing

After you choose your variable names, you should describe their meaning and/or purpose. Since your names should ideally imply thier purpose, you should keep your descriptions very brief. You have different options for where to write the descriptions:

Generally, you should avoid introducing variables in the "middle" of your program.

6.3 Named Constants

To keep your code relatively general, you should avoid a process called hard coding, in which variables and other elements rely on specific values. For instance, suppose you need to input a sequence of values. If you "hard code" your program to accept only ten numbers in the middle of the program, your program is inflexible. Instead, your program should accept STOP values, where STOP is assigned elsewhere, perhaps even to 10. By placing using a variable assignment instead of a specific number, you or another programmer could easily identify the variable that controls the amount of input and change it. Such variables that replace values are called named constants. Sometimes a named constant is so important that you never want the value to change in the midst of the program. Unlike MATLAB, some languages allow you to prevent assignment with special forms of syntax. Variables that cannot change value are called constants. Generally, named constants and constants are written in uppercase.

6.4 Global vs Local

Local variables are visible within a function but not other functions or scripts outside of the function. Even the base workspace, the memory location of the variables that you enter in the command window, cannot "see" local variables inside a function. So, you may use a variable x inside the command window and inside every function M-File with no conflict. However, if you discover that a certain variable value is crucial to many functions, you may label that variable as global to ensure that every function will use the same name and variable. In general, global variables are dangerous, because they are difficult to trace and may substantially alter a program's behavior. So, you should primairly use local variables and save global variables for very specific occasions. Consult Local and Global Variables inside M-File Programming for more information. MATLAB style dictates that you should indicate global variables with uppercase letters, as you would a named constant.

6.5 Predefined Values

MATLAB defines a collection of very useful variables that you should use rather than reinventing. See Local and Global Variables > Special Values for a list.

Top



7. Expressions

Expressions are statements that combine operators and values to produce a value.

7.1 Spacing

Instead of writing expressions, like 1+2/(3^(4-5)), which are relatively unreadable, you should insert whitespace in between operators and values. Using the same example, you would write 1 + 2 / ( 3 ^ (4 - 5) ), which is a bit easier on the eyes.

7.2 Parentheses

Rather than relying on operator precedence and associativity to determine the result of an expression, use parentheses to clarify an operation. For example, although the left associativity of minus dictates that 1-2-3 is -4, you should write the same expression as (1-2)-3, which is much more clear. However, excessive parentheses detract from clarity, as in the expression ((1+2)*(2*(1-2))).

7.3 Variables

For a complete set of rules, refer to Section 6.

7.4 Operators

Beware of the difference between equals (==) and assign (=):

Beware of round-off error: Top

8. Arrays [UNDER CONSTRUCTION]
Top
9. Whitespace

Most languages allow for unlimited whitespace, which is composed of spaces, tabs, and new lines around and in between language elements. Although you may not split an element, such as a keyword, you may freely place spaces between elements. Following the model of paragraphs and indentation, programmers have discovered that placing spaces at the beginning of each line, which is called indentation,  improves clarity and ease of programming. This section describes situations in which you will use indentation.

9.1 Structures and Substructures

Rather than referring to code as individual statements and comments, think of each line as either a structure or substructure:

A lines of code typically have one of the following forms: The following sections demonstrate the use of these forms.

****
old notes that I using to write new stuff:

9.1.1 Form 1

notion of "equivalence"/preference/group
statements that form a group, or a block, are executed in succession to perform steps in a specific task... thus have same "level" of importants... thus flush with eachother, not indented -- group of statements forms a structure

example? (comments, statements)

9.1.2 Form 2

in between structures/groups of statements insert blank lines to indicate where one task ends and another begins -- may also use
to sep structures from substructures

examples?

9.1.3 Form 3

indentation to indicate a substructure of a structure -- substructure activates as part of the overall task of the structure

examples? (comments with statements, compound statements)

9.1.4 Form 4
combines all forms
 
 

For instance, you may see the following styles:

In both versions, the comment describes the input statement. Thus, the comment starts a new structure, which includes the input statement as a substructure: This principle is especially important because good programming involves breaking larger problems into smaller problems. The way the sub-problems fit/nest into the larger problems should be immediately apparent from the code for maximum clarity. The principle above provides that clarity with a simple, unifying principle consistent with our other conventions for indentation.

However, you should be aware that not everyone uses this convention. Sometimes it is not relevant, and sometimes there are rules/forces against it. For example, CS312 tends to use a rather different program language to write rather different programs, in which other styles might be appropriate. (Another example is that J and M instructors often use a variety of editors with different methods for formatting.)

You should apply the principle in your own code for CS100, but if you would rather not, keep in mind that your project scores will not suffer unless you make a handful of other errors -- you can get a perfect score if you make only a few errors.

9.2 Statement Comments

9.3 Selection Statements

9.4 Repetition Statements
 

Top



10. Functions
[under construction]
Since we tend to think of functions as black boxes, their behaviour should be clear to a user:
Clearly specify inputs and outputs using "Preconditions" and "Postconditions".
However, details of implementation of the function usually do not matter and are not part of the specification.

Preconditions specify:

Postconditions specify: What this means in terms of MATLAB commenting: Top


Top

Top
Top


Top

Top

Top