You are on page 1of 6

AERO

300 MATLAB Programming Style Guide


Programming style is the set of rules of guidelines used when writing source code for a computer program. Proper programming style is still a topic of debate in the programming community and adherence to any specific style depends on the programming language used, size of the project, and personal preference. Programming style can be thought of as the formatting used for a technical paper, there are many different technical formats in use today, you are already familiar with AIAA format, but they all achieve the common goal of being aesthetically pleasing and easier to understand. Note that you will NOT be graded on style and the guidelines presented here are simply that, guidelines, feel free to develop your own style that works for you. Paying attention to style may be annoying at first but it is meant to help you write code that is easier to debug and understand. WHITE SPACE A common mistake that I see new programmers make in regards to style is the lack of white space. White space is any space, tab, or carriage return used in your code. To convey this issue I present an example, each script does the exact same thing but it should be obvious which script you would rather be working with. The scripts shown multiply two matrices together then using a given solution vector solves the linear system. script1.m
A=[1,4,5;4,2,8;9,4,6];B=[5,3,6;2,1,7;4,3,1]; b=[3,2,1]';C=A*B;x=C\b; fprintf(' x1: %f\n x2: %f\n x3: %f\n',x(1),x(2),x(3));

script2.m

A = [1, 4, 5; 4, 2, 8; 9, 4, 6]; B = [5, 3, 6; 2, 1, 7; 4, 3, 1]; b = [3, 2, 1]'; C = A*B; x = C\b;

fprintf(' x1: %f\n x2: %f\n x3: %f\n',x(1),x(2),x(3));

Each script will give the exact same output but it should be clear that it is much easier to read script2.m. White space in MATLAB is used solely to enhance readability so use your own discretion for what to do in a given situation. Surround logical operators (<,<=,>,>=,==,~=) and the assignment operator (=) with spaces.
val = 5; if (val < 5) || (val > 10), end;

Putting a space before and after an operator is often called space padding. Sometimes it is appropriate to space pad arithmetic operators (+, -, /, ^). Most often I will space pad the + and / operator and not the * and ^ operators.
val = (5*2 + 6/2)^2;

Commas should be followed by a space.


fun(alpha, beta, gamma); fun(alpha,beta,gamma);

This rule really comes down to the tradeoff between readability and compactness, some functions can have many input arguments so just do what looks best. MATLAB keywords should be followed by a space. Keywords are special words in MATLAB that are used in code. Going into the command window and typing >> iskeyword will display a list of all the MATLAB keywords. Many of these will look very familiar if you have programmed in any other language but their behavior may be slightly different. Keywords can also be easily identified because they will turn blue when in MATLAB, however not all code will be color coded and having a space after the keyword helps differentiate it from the other code. Nested loops and if statements should be indented.
for p = 1:10 for q = 5:12 disp(p*q); end end

The indentation makes it much simpler to tell which loop a statement is in. If there happen to be a lot of loops or if statements in my code I will often change my tab length to 2 spaces instead of the default 4. This option can be changed in File -> Preferences -> Editor/Debugger -> Tab. Use alignment to help readability
fxy = (1/4*h*k)*(fun(x fun(x fun(x fun(x + + h, h, h, h, y y y y + + k) - ... k) - ... k) + ... k));

I = [1, 0, 0; 0, 1, 0; 0, 0, 1];

Note that when defining a matrix in MATLAB the ellipses () are not required after each line, but they must be present whenever a statement extends over multiple lines. Logical Blocks of code should be separated by more than one blank line and into cells. Splitting up code into logical blocks helps the readability and the debugging process. In most languages adding a few blanks lines and a comment on what the block of code does is common, MATLAB however has cell mode which is very handy for breaking up code and can be activated by using the double percent (%%). Go to http://blogs.mathworks.com/videos/2011/07/26/starting-in-matlab-cell-mode- scripts/ for a good introduction to cell mode. COMMENTS The second blunder I commonly see students make is that they dont properly comment their code. A comment is used to add programmer readable annotations to the source code of a program and is ignored by the computer when the code is run. Comments add important information to the code in order to explain usage, give reference information, and explain decisions, etc. The rule of thumb is that comments should be added to code as its being written and not after.

Comments should agree with the code This may seem trivial but I have seen the code say one thing and the comment say something else too many times, and often both statements are incorrect in which case it is extra confusing to whomever is reading your code. A comment should add extra information to the code not just restate what the code is doing. Comments should be easy to read Comments should be indented the same as the piece of code being commented on. The % symbol should be followed by a space. Full sentences are preferred but not always practical. An easy way to check if there is appropriate commenting in a code is that someone should be able to read just the comments with no knowledge of syntax of the language you are using and understand what the program is doing and why. All functions and scripts should have a comment header The size and information given in the header will vary but at the very least you need to put your name on every piece of code you write. For user written functions the >> help myFunction command will display the first block of comments for the function and comment headers should be created with this in mind. Common things to include in the header are name, date written, a description of what the function does and how to use it, units used for calculations, a description of the variables used and other user defined functions that are needed to run the function. Here is an example header for a function that calculates Mach number.
%% calculateMachNumber % Jason Daniel % 1/7/2013 % % Function calculates mach number using the ideal gas law % Input: % vel - flow velocity (m/s) % gamma - ratio of specific heats () % temp - static flow temperature (K) % Output: % machNumber - mach number of flow () % % Dependences: % None % % Usage: % M = calculateMachNumber(1200, 1.4, 532); % %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ function [machNumber] = calculateMachNumber(vel, gamma, temp)

Variable and Function Names

Variable names should indicate what the variable is or does. Single variable names are commonly used but should be avoided if possible. For example compare the two statements.
a = b * c; weekly_pay = hours_worked * pay_rate;

Each statement simply takes two values, multiplies them and stores the result but the second line is much easier to understand what is being done, it gives the line of code context. Variable names should be in mixed case or underscore delimited Mixed case, also called camel case, means that the first letter for every word, except the first, in a variable name is capitalized. For example
temperature firstDerivative volumeOfCylinder

Underscore delimited means that there is an underscore after each word, all words should be lowercase.
first_Derivative volume_Of_Cylinder

The prefix n should be used for variables representing the number of objects
nObservations nRows

Global variables should be underscore delimited and in all caps This is also a good practice to use for constants that should not be changed
global GRAVITATIONAL_PARAMETER; global N_PARTICLES; PI = 3.1415;

References MATLAB Programming Style Guidelines Richard Johnson 2002

You might also like