Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

MATLAB Programming Style Guidelines | PHYS 241, Exams of Physics

Material Type: Exam; Class: Computational Mechanics; Subject: Physics; University: New Mexico Institute of Mining and Technology; Term: Fall 2002;

Typology: Exams

Pre 2010

Uploaded on 08/08/2009

koofers-user-d27
koofers-user-d27 🇺🇸

10 documents

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
MATLAB Programming Style Guidelines
Richard Johnson
Version 1.5 October 2002
Copyright © 2002 Datatool
“Language is like a cracked kettle on which we beat tunes to dance to, while all the time
we long to move the stars to pity.” Gustave Flaubert, in Madame Bovary
Table of Contents
Introduction.............................................................................................................................................. 2
Naming Conventions .............................................................................................................................2
Variables.............................................................................................................................................. 2
Constants............................................................................................................................................. 4
Structures ............................................................................................................................................ 4
Functions ............................................................................................................................................. 4
General ................................................................................................................................................ 6
Files and Organization........................................................................................................................... 6
M Files.................................................................................................................................................. 6
Input and Output................................................................................................................................. 7
Statements .............................................................................................................................................. 7
Variables.............................................................................................................................................. 7
Loops.................................................................................................................................................... 8
Conditionals......................................................................................................................................... 8
General ................................................................................................................................................ 9
Layout, Comments and Documentation ...........................................................................................10
Layout ................................................................................................................................................ 10
White Space...................................................................................................................................... 11
Comments ......................................................................................................................................... 12
Documentation.................................................................................................................................. 13
References ............................................................................................................................................ 13
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download MATLAB Programming Style Guidelines | PHYS 241 and more Exams Physics in PDF only on Docsity!

MATLAB Programming Style Guidelines

Copyright © 2002 Datatool “Language is like a cracked kettle on which we beat tunes to dance to, while all the time we long to move the stars to pity.” Gustave Flaubert, in Madame Bovary

 - Version 1.5 October Richard Johnson 
  • Introduction.............................................................................................................................................. Table of Contents
  • Naming Conventions
    • Variables..............................................................................................................................................
    • Constants.............................................................................................................................................
    • Structures
    • Functions
    • General
  • Files and Organization...........................................................................................................................
    • M Files..................................................................................................................................................
    • Input and Output.................................................................................................................................
  • Statements
    • Variables..............................................................................................................................................
    • Loops....................................................................................................................................................
    • Conditionals.........................................................................................................................................
    • General
  • Layout, Comments and Documentation
    • Layout
    • White Space......................................................................................................................................
    • Comments
    • Documentation..................................................................................................................................
  • References

Introduction

Advice on writing MATLAB code usually addresses efficiency concerns, with recommendations such as “Don’t use loops.” This document is different. Its concerns are correctness, clarity and generality. The goal of these guidelines is to help produce code that is more likely to be correct, understandable, sharable and maintainable. As Brian Kernighan writes, “Well-written programs are better than badly-written ones -

  • they have fewer errors and are easier to debug and to modify -- so it is important to think about style from the beginning.”

This document lists MATLAB coding recommendations consistent with best practices in the software development community. These guidelines are generally the same as those for C, C++ and Java, with modifications for Matlab features and history. The recommendations are based on guidelines for other languages collected from a number of sources and on personal experience. These guidelines are written with M ATLAB in mind, and they should also be useful for related languages such as Octave, Scilab and O-Matrix.

Guidelines are not commandments. Their goal is simply to help programmers write well. Many organizations will have reasons to deviate from them.

“You got to know the rules before you can break ‘em. Otherwise it’s no fun.” Sonny Crockett in Miami Vice

M ATLAB is a registered trademark of The MathWorks, Inc. In this document the acronym TMW refers to The MathWorks, Inc.

This writeup is dedicated to those who care enough to improve.

Naming Conventions

Patrick Raume, “A rose by any other name confuses the issue.”

Establishing a naming convention for a group of developers can become ridiculously contentious. This section describes a commonly used convention. It is especially helpful for an individual programmer to follow a naming convention.

Variables

The names of variables should document their meaning or use.

Variable names should be in mixed case starting with lower case. This is common practice in the C++ development community. TMW sometimes starts variable names with upper case, but that usage is commonly reserved for types or structures in other languages. linearity, credibleThreat, qualityOfLife An alternative technique is to use underscore to separate parts of a compound variable name. This technique, although readable, is not commonly used for variable names in other languages. Another consideration for using underscore in variable names in legends is that the Tex interpreter in M ATLAB will read underscore as a switch to subscript.

Avoid isNotFound

Acronyms, even if normally uppercase, should be mixed or lower case. Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type would have to be named dVD, hTML etc. which obviously is not very readable. When the name is connected to another, the readability is seriously reduced; the word following the abbreviation does not stand out as it should. Use html, isUsaSpecific, checkTiffFormat() Avoid hTML, isUSASpecific, checkTIFFFormat()

Avoid using a keyword or special value name for a variable name. MATLAB can produce cryptic error messages or strange results if any of its reserved words or builtin special values is redefined. Reserved words are listed by the command iskeyword. Special values are listed in the documentation.

Constants

Named constants (including globals) should be all uppercase using underscore to separate words. This is common practice in the C++ development community. Although TMW may appear to use lower case names for constants, for example pi, such builtin constants are actually functions. MAX_ITERATIONS, COLOR_RED

Constants can be prefixed by a common type name. This gives additional information on which constants belong together and what concept the constants represent. COLOR_RED, COLOR_GREEN, COLOR_BLUE

Structures

Structure names should begin with a capital letter. This usage is consistent with C++ practice, and it helps to distinguish between structures and ordinary variables.

The name of the structure is implicit, and need not be included in a fieldname. Repetition is superfluous in use, as shown in the example. Use Segment.length Avoid Segment.segmentLength

Functions

The names of functions should document their use.

Names of functions should be written in lower case. It is clearest to have the function and its m-file names the same. Using lower case avoids potential filename problems in mixed operating system environments. getname(.), computetotalwidth(.) There are two other function name conventions commonly used. Some people prefer to use underscores in function names to enhance readability. Others use the naming convention proposed here for variables.

Functions should have meaningful names. There is an unfortunate MATLAB tradition of using short and often somewhat cryptic function names—probably due to the DOS 8 character limit. This concern is no longer relevant and the tradition should usually be avoided to improve readability. Use computetotalwidth() Avoid compwid() An exception is the use of abbreviations or acronyms widely used in mathematics. max(.), gcd(.) Functions with such short names should always have the complete words in the first header comment line for clarity and to support lookfor searches.

Functions with a single output can be named for the output. This is common practice in TMW code. mean(.), standarderror(.)

Functions with no output argument or which only return a handle should be named after what they do. This practice increases readability, making it clear what the function should ( and possibly should not) do. This makes it easier to keep the code clean of unintended side effects. plot(.)

The prefixes get/set should generally be reserved for accessing an object or property. General practice of TMW and common practice in C++ and Java development. A plausible exception is the use of set for logical set operations. getobj(.); setappdata(.)

The prefix compute can be used in methods where something is computed. Consistent use of the term enhances readability. Give the reader the immediate clue that this is a potentially complex or time consuming operation. computweightedaverage(); computespread()

The prefix find can be used in methods where something is looked up. Give the reader the immediate clue that this is a simple look up method with a minimum of computations involved. Consistent use of the term enhances readability and it is a good substitute for get. findoldestrecord(.); findheaviestelement(.);

The prefix initialize can be used where an object or a concept is established. The American initialize should be preferred over the British initialise. Abbreviation init should be avoided. initializeproblemstate(.);

The prefix is should be used for boolean functions. Common practice in TMW code as well as C++ and Java. isoverpriced(.); iscomplete(.) There are a few alternatives to the is prefix that fit better in some situations. These include the has , can and should prefixes: hasLicense(.); canEvaluate(.); shouldSort(.);

Complement names should be used for complement operations. Reduce complexity by symmetry.

Partitioning All subfunctions and many functions should do one thing very well. Every function should hide something.

Use existing functions. Developing a function that is correct, readable and reasonably flexible can be a significant task. It may be quicker or surer to find an existing function that provides some or all of the required functionality.

Any block of code appearing in more than one m-file should be considered for packaging as a function. It is much easier to manage changes if code appears in only one file. “Change is inevitable…except from vending machines.”

Subfunctions A function used by only one other function should be packaged as its subfunction in the same file. This makes the code easier to understand and maintain.

Test scripts Write a test script for every function. This practice will improve the quality of the initial version and the reliability of changed versions. Consider that any function too difficult to test is probably too difficult to write. Boris Beizer: “More than the act of testing, the act of designing tests is one of the best bug preventers known.”

Input and Output

Make input and output modules. Output requirements are subject to change without notice. Input format and content are subject to change and often messy. Localizing the code that deals with them improves maintainability. Avoid mixing input or output code with computation, except for preprocessing, in a single function. Mixed purpose functions are unlikely to be reusable.

Format output for easy use. If the output will most likely be read by a human, make it self descriptive and easy to read. If the output is more likely to be read by software than a person, make it easy to parse. If both are important, make the output easy to parse and write a formatter function to produce a human readable version.

Statements

Variables and constants

Variables should not be reused unless required by memory limitation. Enhance readability by ensuring all concepts are represented uniquely. Reduce chance of error from misunderstood definition.

Related variables of the same type can be declared in a common statement. Unrelated variables should not be declared in the same statement. It enhances readability to group variables. persistent x, y, z global REVENUE_JANUARY, REVENUE_FEBRUARY

Consider documenting important variables in comments near the start of the file. It is standard practice in other languages to document variables where they are declared. Since MATLAB does not use variable declarations, this information can be provided in comments. % pointArray Points are in rows with coordinates in columns.

Consider documenting constant assignments with end of line comments. This gives additional information on rationale, usage or constraints. THRESHOLD = 10; % Maximum noise level found by experiment.

Globals

Use of global variables should be minimized. Clarity and maintainability benefit from argument passing rather than use of global variables. Some use of global variables can be replaced with the cleaner persistent or with getappdata.

Use of global constants should be minimized. Use an m-file or mat file. This practice makes it clear where the constants are defined and discourages unintentional redefinition. If the file access is undesirable, consider using a structure of global constants.

Loops

Loop variables should be initialized immediately before the loop. This improves loop speed and helps prevent bogus values if the loop does not execute for all possible indices. result = zeros(nEntries,1); for index = 1:nEntries result(index) = foo(index); end

The use of break and continue in loops should be minimized. These constructs can be compared to goto and they should only be used if they prove to have higher readability than their structured counterpart.

The end lines in nested loops can have comments Adding comments at the end lines of long nested loops can help clarify which statements are in which loops and what tasks have been performed at these points.

Conditionals

Complex conditional expressions should be avoided. Introduce temporary logical variables instead. By assigning logical variables to expressions, the program gets automatic documentation. The construction will be easier to read and to debug. if (value>=lowerLimit)&(value<=upperLimit)&~ismember(value,… valueArray) : end should be replaced by: isValid = (value >= lowerLimit) & (value <= upperLimit); isNew = ~ismember(value, valueArray);

Use parentheses. MATLAB has documented rules for operator precedence, but who wants to remember the details? If there might be any doubt, use parentheses to clarify expressions. They are particularly helpful for extended logical expressions.

The use of numbers in expressions should be minimized. Numbers that are subject to change usually should be named constants instead. If a number does not have an obvious meaning by itself, readability is enhanced by introducing a named constant instead. It can be much easier to change the definition of a constant than to find and change all of the relevant occurrences of a literal number in a file.

Floating point constants should always be written with a digit before the decimal point. This adheres to mathematical conventions for syntax. Also, 0.5 is more readable than .5; it is not likely to be read as the integer 5. Use THRESHOLD = 0.5; Avoid THRESHOLD = .5;

Floating point comparisons should be made with caution. Binary representation can cause trouble, as seen in this example. shortSide = 3; longSide = 5; otherSide = 4; longSide^2 == (shortSide^2 + otherSide^2) ans = 1 scaleFactor = 0.01; (scaleFactorlongSide)^2 == ((scaleFactorshortSide)^2 + … (scaleFactor*otherSide)^2) ans = 0

Layout, Comments and Documentation

Layout

The purpose of layout is to help the reader understand the code. Indentation is particularly helpful for revealing structure.

Content should be kept within the first 80 columns. 80 columns is a common dimension for editors, terminal emulators, printers and debuggers, and files that are shared between several people should keep within these constraints. Readability improves if unintentional line breaks are avoided when passing a file between programmers.

Lines should be split at graceful points. Split lines occur when a statement exceeds the suggested 80 column limit. In general:

  • Break after a comma or space.
  • Break after an operator.
  • Align the new line with the beginning of the expression on the previous line.

totalSum = a + b + c + … d + e; function (param1, param2,… param3) setText ([‘Long line split’ … ‘into two parts.’]);

Basic indentation should be 3 or 4 spaces. Good indentation is probably the single best way to reveal program structure. Indentation of 1 is too small to emphasize the logical layout of the code. Indentation of 2 is sometimes suggested to reduce the number of line breaks required to stay within 80 columns for nested statements, but MATLAB is usually not deeply nested. Indentation larger than 4 can make nested code difficult to read since it increases the chance that the lines must be split. Indentation of 4 is the current default in the M ATLAB editor; 3 was the default in some previous versions.

Indentation should be consistent with the M ATLAB Editor. The MATLAB editor provides indentation that clarifies code structure and is consistent with recommended practices for C++ and Java.

In general a line of code should contain only one executable statement. This practice improves readability and allows JIT acceleration.

Short single statement if, for or while statements can be written on one line. This practice is more compact, but it has the disadvantage that there is no indentation format cue. if(condition), statement; end while(condition), statement; end for iTest = 1:nTest, statement; end

White Space

White space enhances readability by making the individual components of statements stand out.

Surround =, &, and| by spaces. Using space around the assignment character provides a strong visual cue separating the left and right hand sides of a statement. Using space around the binary logical operators can clarify complicated experessions. simpleSum = firstTerm+secondTerm; Conventional operators can be surrounded by spaces. This practice is controversial. Some believe that it enhances readability. simpleAverage = (firstTerm + secondTerm) / two; 1 : nIterations

Commas can be followed by a space. These spaces can enhance readability. Some programmers leave them out to avoid split lines. foo(alpha, beta, gamma) foo(alpha,beta,gamma)

Semicolons or commas for multiple commands in one line should be followed by a space character. Spacing enhances readability. if (pi>1), disp(‘Yes’), end

Keywords should be followed by a space. This practice helps to distinguish keywords from functions.

Function header comments should describe any side effects. Side effects are actions of a function other than assignment of the output variables. A common example is plot generation. Descriptions of these side effects should be included in the header comments so that they appear in the help printout.

In general the last function header comment should restate the function line. This allows the user to glance at the help printout and see the input and output argument usage.

Writing the function name using uppercase in the function header is controversial. This is a MathWorks practice, which is intended to make the function name prominent. Many other authors do not follow this practice. Its disadvantage is that in code the function name should usually be in lower case.

Avoid clutter in the help printout of the function header. It is common to include copyright lines and change history in comments near the beginning of a function file. There should be a blank line between the header comments and these comments so that they are not displayed in response to help.

All comments should be written in English. In an international environment, English is the preferred language.

Documentation

Formal documentation To be useful documentation should include a readable description of what the code is supposed to do (Requirements), how it works (Design), which functions it depends on and how it is used by other code (Interfaces), and how it is tested. For extra credit, the documentation can include a discussion of alternative solutions and suggestions for extensions or maintenance. Dick Brandon: “Documentation is like sex; when it's good, it's very, very good, and when it's bad, it's better than nothing.”

Consider writing the documentation first. Some programmers believe that the best approach is “Code first and answer questions later.” Through experience most of us learn that developing a design and then implementing it leads to a much more satisfactory result. Development projects are almost never completed on schedule. If documentation and testing are left for last, they will get cut short. Writing the documentation first assures that it gets done and will probably reduce development time.

Changes. The professional way to manage and document code changes is to use a source control tool. For very simple projects, adding change history comments to the function files is certainly better than nothing. % 24 November 1971, D.B. Cooper, exit conditions modified.

References

The Practice of Programming, Brian Kernighan and Rob Pike

The Pragmatic Programmer, Andrew Hunt, David Thomas and Ward Cunningham

Java Programming Style Guidelines, Geotechnical Software Services

Code Complete, Steve McConnel - Microsoft Press

C++ Coding Standard, Todd Hoff

© 2002 Datatool. All rights reserved.