Programming standards are guidelines that one uses to write well-documented code that is understandable by others and to develop good programming habits. All MATLAB code submissions in this course must follow the standards in this document.

Why Follow Programming Standards?

  • Make code easier to understand. Your code must be readable by team members, graders, instructors, and eventually co-workers and supervisors. You will read code written by others. Well-written code makes its purpose and logic clear and is easily used by others.
  • Help minimize errors. Readable, easy-to-follow code helps minimize errors and allows for easier debugging when errors do occur.
  • Develop good habits. Learning these standards now will help you be an efficient programmer and help you resist poor programming habits in the future.

Note: Course materials will attempt to abide by these standards whenever possible to serve as an example. However, some course materials may exclude headers and comments to save space; this is not an option for your assignments.

Use the Appropriate Code Template

You must use an ENGR 132 template for MATLAB files submitted with an assignment. There are two template types, one for script files and one for function files. Use the correct template for the type of MATLAB code you are developing. Some problem sets have problem-specific templates; use those templates when provided. Otherwise, you can download a generic template from your course’s site.

Each template has a header block that starts on the first line of the code for scripts or on the second line for functions. You must complete the header block for each m-file that you submit for a grade in ENGR 132.

The header is the comment block at the top of the program. It needs to contain relevant problem, program, and author information to help others understand what the program does, how to use it, and who wrote it. All m-files submitted in ENGR 132 need a complete header. All headers require a program description and author information. Function m-files also require help lines to explain the function call and its inputs and outputs.

The header information appears in the MATLAB Command Window when a user calls MATLAB’s help functionality to learn about the script or function. The header should provide the user with all information necessary to use the file.

Program Description – all scripts and functions

The program description briefly describes the purpose or expected outcome of the program. The program description must be clear and concise. Clear descriptions can be understood without confusion and concise descriptions are not redundant or superfluous. Anyone looking at your code, including your grader, should be able to use your program description to quickly understand what the code should do.

Author Information – all scripts and functions

All m-files need author information. Complete the appropriate lines of the header with the following information:

  • Assignment: State the assignment number and the problem number (e.g., A04, Problem 2).
  • Author: Add your name and your Purdue email address with your official login (no aliases).
  • Team ID: Add your section and team number. For early assignments (prior to being assigned to a team), list only your section number.
  • Academic Integrity:
    • If you worked with another student to complete the assignment, place an X within the [] to acknowledge the collaboration and that you maintained academic integrity.
    • If you worked with another student, list their name and official Purdue email. Add additional lines if you worked with more than one peer. Read the course Academic Integrity document for more information about working together.

Function Call – functions only

The function call line is a help line that demonstrates how to call the function. This line should not contain the word “function”.

Input Argument and Output Arguments – functions only

Functions can have input arguments, output arguments, both, or neither. Define each input argument and output argument with a concise description that includes units as appropriate. If the function does not have input or output arguments, then indicate ‘none’ in the appropriate location in the header.

This is particularly important for inputs because there is no place to describe them in the body of the code.

Organize Code Properly

Well organized code is easier to understand and debug. The standard ENGR 132 template has the following sections:

  • Initialization: Assign constants or variables, import data, and receive input from a user.
  • Calculations: Perform calculations and manipulate inputs.
  • Formatted Text & Figure Displays: Generate results to display, including figures and print statements.
  • Results: Paste Command Window outputs or displays as comments; use when required in a problem.
  • Analysis: Answer questions assigned in a given problem. These are only present in problem-specific templates.

Use these sections whenever possible. If the problem has a problem-specific template, then you must use the sections provided in that template.

Comment Your Code

Comments provide information to help users understand the code. Use comments to inform others (particularly the grader) what exactly you are attempting to implement. MATLAB uses % to define a comment. MATLAB ignores all text and characters that follow a % when it executes that line.

  • Use comments to describe the purpose of all variables and constants defined in the initialization section of your code. Include units where applicable.
  • Do not use %{ for multi-line comments.
  • Use block comments to describe related sets of commands that briefly explains the functionality of the code block. Block comments must be clear and concise.
  • Block comments can reduce or eliminate the need for individual comments on each variable assigned through calculations.

Example of block commenting:

% Plot force vs time and format for technical presentation
plot(test_time,applied_force,'*')
title('Application of Force during Iron Beam Stress Test')
xlabel('Time (s)')
ylabel('Force (N)')
grid on

Format for Readability

Code formatting shows the code structure and makes the code more readable to other programmers. Good formatting uses whitespace and indentation to organize the code.

Whitespace – all types of code

Whitespace helps with readability. Consider these two examples.

Example 1

%% Example 1: poor use of whitespace
% Define ball bearing parameters
bb_diameter=0.25;% ball diameter, cm
steel_density=8.05;% density of steel, g/cm^3
% Calculate the mass of the ball bearing in grams
bb_radius=bb_diameter/2;
bb_vol=4*pi*bb_radius^3/3;
bb_mass=steel_density*bb_vol;
% Display the mass to the Command Window
fprintf('The ball bearing mass is %.2f grams.\n',bb_mass)

Example 2

%% Example 2: good use of whitespace

% Define ball bearing parameters
bb_diameter = 0.25; % ball diameter, cm
steel_density = 8.05; % density of steel, g/cm^3

% Calculate the mass of the ball bearing in grams
bb_radius = bb_diameter/2;
bb_vol = 4 * pi * bb_radius^3 / 3;
bb_mass = steel_density * bb_vol;

% Display the mass to the Command Window
fprintf('The ball bearing mass is %.2f grams.\n', bb_mass)

Example 2 uses whitespace to make the code easier to read and understand. To ensure your code uses whitespace appropriately,

  • Place an additional line between sections or code blocks to help “group” the code.
  • Place a space between operators and operands to improve readability. For example, y = y - g is easier to read and quickly understand than y=y-g.

Indentation – specific types of code structures

Indentation establishes the structure of decisions and loops. Indent selection structures, repetition structures, and nested structures. The following examples demonstrate proper indentation for various structures.

%% Example 3: selection structure with indentation
if r == 1
new_temp = (temp_matrix(r+1) + temp_matrix(r))/2;
else
new_temp = (temp_matrix(r-1) + temp_matrix(r))/2;
end
%% Example 4: repetition structure with indentation
new_temp = temp_matrix(n,m);
temp_increase = 1;
while new_temp < boil_point
new_temp = new_temp + temp_increase;
end
%% Example 5: nested structure with indentation
if (n < 2) || (m < 2)
fprintf('Please enter a matrix with dimensions of at least 2x2')
else
for x = 1:n
for y = 1:m
new_temp(x,y) = temp_update(temp_matrix,x,y);
end
end
end

Use Appropriate Variables

Use descriptive variable names that make the variable’s purpose clear without having to look at any more code. Consider these examples:

Code Snippet 1


%% INITIALIZATION
x = 100
y = 88

Code Snippet 2


%% INITIALIZATION
numStudents = 100
avgGrade = 88

The variables x and y are vague and non-descriptive while numStudents and avgGrade clearly describe what they represent.

  • Variable names should be valid, descriptive, and not overwrite built-in MATLAB functions or values.
  • Assign only one variable per line.
  • Assign all calculations in your code to variables.

Suppress Command Outputs

Your MATLAB code should only display values and text that you deliberately want to see in the Command Window. MATLAB displays all variable assignments and calculation results by default. You must use a semicolon (;) at the end of those commands to suppress the display of those values.

Look at the following code example:

Code A

% Calculate area of a triangle &
% parallelogram when given base
% and height
base = 10;
Height = 8;
area_tri = 0.5 * base * Height;
area_para = base * Height;

Notice that there is a semicolon at the end of each line. The semicolons tell MATLAB that it should not display the values of the assigned variables base, Height, area_tri, and area_para to the Command Window. While you are developing and debugging your code, you may want to see the result of your calculations and variable assignments so you can verify that the code is working properly. But once you have the code working, you need to suppress all outputs unless specifically told otherwise.

Note that the semicolon is not needed on built-in MATLAB functions that do not get assigned to a variable, such as plot or fprintf.

Minimize Hardcoding

To hardcode means to use numbers in calculations instead of variables. Variables make code adaptable and powerful. If you can assign values to variables, then do so. The only hardcoded values in your code should be coefficients and array indexing values.

For example, you need to write code to determine the area of a triangle, A = 0.5*b*h, and the area of a parallelogram, A = b*h, where the base is 10 units and the height is 8 units. Consider these two pieces of code:

Code A (same as example above)

% Calculate area of a triangle &
% parallelogram when given base
% and height
base = 10;
Height = 8;
area_tri = 0.5 * base * Height;
area_para = base * Height;

Code B

% Calculate area of a triangle &
% parallelogram when given base
% and height
area_tri = 0.5 * 10 * 8;
area_para = 10 * 8;

Code A follows good programming standards regarding hardcoding. It assigns values to the variables base and Height and then uses those variables to calculate the areas. Code B calculates the areas directly from hardcoded values. Note that 0.5 is hardcoded in both equations because 0.5 is a coefficient, not a variable.

It is also considered hardcoding when you manually enter data values as arrays when you are provided a data file that can be imported into MATLAB. If you are given a data file, import those values into MATLAB using an appropriate built-in function; do not type the values into the script or function directly.

Hardcoding makes it difficult to adapt or update the code. In Code A, you can update the variables with new values and all calculations using those variables will update accordingly. If you want to update Code B with new values, you must find all the old values and replace each instance with the updated values. That process is inefficient and prone to error.

Another benefit of variables is that they allow conversion from a script to a function. The use of variables in Code A makes it easily translated into a function that can accept user inputs for base and height. Code B does not have that flexibility.

Hardcoding and array indexing

In general, it is not considered hardcoding to manually code array indices in straightforward programming. For example, you want to make the third row of a matrix into its own variable.

matrixA = magic(5,5);         % create a 5x5 magic square matrix
matrixA_row3 = matrixA(3,:); % 3rd row, all columns of matrixA

This example has no improper hardcoding.

But, hardcoding an index value is improper if the index value can be found programmatically (i.e., you can use MATLAB to figure out the index value) AND that index value would change if you changed the data/array values. This can be done in more complex programming later in the course.

Hardcoding and repetition structures

It is not hardcoding to increment an iteration counter or index while controlling a repetition structure. It is also not hardcoding to define the first element of a looping control vector as 1.

For example, the command for index = 1:5:100 does not contain hardcoding for the 1 or the 5. The context of the problem would determine if the 100 is hardcoded or if it should be determined within the program.

Global variables

Avoid global variables in this course. They can easily limit the flexibility of your program, cause name conflicts, unintentionally overwrite variables, and add confusion while debugging.