When you write MATLAB code, it is easy to focus entirely on getting the program to work. You write the commands, fix the errors, run the script, and move on. But if you come back to that same file a few weeks later or someone else has to read it you quickly realize that working code is not always easy-to-understand code.
- What Is a Comment in MATLAB?
- Why Comments Matter in MATLAB Code
- How to Add Basic Comments in MATLAB
- Explain Why Instead of Repeating What the Code Does
- How to Comment MATLAB Functions
- Use %% to Organize Long MATLAB Scripts
- When Inline Comments Make Sense
- How to Use Block Comments
- Keep Comments Close to the Code They Explain
- Do Not Let Comments Become Outdated
- Keep Comments Short and Easy to Read
- Commenting Out MATLAB Code
- Comments and MATLAB Live Scripts
- A Simple Before-and-After Example
- Common MATLAB Commenting Mistakes to Avoid
- A Practical Way to Comment Your MATLAB Code
- 1. Look at the purpose of the code
- 2. Look for decisions
- 3. Check function inputs and outputs
- 4. Remove comments that add no information
- 5. Review comments when you edit the code
- Final MATLAB Commenting Checklist
That is where comments help.
A good MATLAB comment gives the reader useful context without explaining things that are already obvious from the code. In my experience, the best comments answer questions such as Why is this value being used? What does this calculation represent? What assumption was made here?
MATLAB has several ways to add comments, from a simple % to section headings and function documentation. Once you know when to use each one, your scripts become much easier to read and maintain.
What Is a Comment in MATLAB?
A comment is text that MATLAB does not execute as part of the program. The most common way to create one is to place a percent sign (%) before the text.
For example:
% Calculate the average temperature.
averageTemp = mean(temperature);
MATLAB ignores the first line when the program runs.
You can also put a short comment after a statement:
averageTemp = mean(temperature); % Average of all measurements
Both approaches are valid. The choice mainly depends on how much information you need to provide.
The important thing is not simply knowing how to add a comment. You need to know when a comment is actually useful.
Why Comments Matter in MATLAB Code
Comments become particularly valuable when a program contains calculations that are not immediately obvious.
Consider this:
x = x * 0.3048;
A reader can see that x is being multiplied by a number, but they may not know why.
A short comment gives the missing context:
% Convert the distance from feet to metres.
x = x * 0.3048;
Now the purpose is clear.
This is one of the main principles I use when commenting code: do not comment simply because you have written code; comment when the reader needs information that the code itself does not provide.
A comment like this is usually unnecessary:
% Add x and y.
z = x + y;
The code already tells us exactly what is happening.
A better comment would explain the reason for the calculation:
% Combine the two measurements before calculating the final value.
z = x + y;
The difference may seem small, but it makes the comment much more valuable.
How to Add Basic Comments in MATLAB
For a normal comment, place % before the text.
% Load the experimental data.
data = readmatrix("experiment.csv");
You can have several comment lines together:
% Load the experimental data.
% Remove invalid measurements.
% Calculate the average response.
If you add a comment at the end of a line, keep it short:
g = 9.81; % Gravitational acceleration in m/s^2
This works particularly well for constants, units, thresholds, and other small pieces of information.
I also recommend leaving a space after %:
% Calculate the result.
rather than:
%Calculate the result.
It is a small formatting detail, but consistent spacing makes a file easier to scan.
Explain Why Instead of Repeating What the Code Does
This is probably the most important MATLAB commenting best practice to remember.
Your code already tells the reader what it is doing. Your comments should provide the missing explanation.
For example:
% Loop through the values.
for i = 1:length(x)
y(i) = x(i)^2;
end
The comment does not add much. The loop itself makes that obvious.
Compare it with:
% Square each measurement before calculating the energy estimate.
for i = 1:length(x)
y(i) = x(i)^2;
end
Now the reader knows why the operation is being performed.
The same idea applies to numerical methods. Suppose you see:
dt = 0.001;
Without context, the number tells you very little.
You could write:
% Use a smaller time step near the transition to improve numerical accuracy.
dt = 0.001;
The comment explains the decision behind the value rather than describing the assignment itself.
How to Comment MATLAB Functions
Functions usually need more documentation than individual lines because someone may use the function without looking at its internal implementation.
MATLAB allows you to put help text immediately below a function definition. That text can then be displayed with MATLAB’s help command.
For example:
function area = circleArea(radius)
% CIRCLEAREA Calculate the area of a circle.
% AREA = CIRCLEAREA(RADIUS) returns the area of a circle
% with the specified radius.
area = pi * radius^2;
end
The first line gives a quick description. The following lines explain how the function is used.
For a more complicated function, it is worth documenting:
- What the function does
- What each input represents
- What the function returns
- Units of measurement
- Important assumptions
- Any unusual behaviour
- A usage example when necessary
For instance:
function velocity = calculateVelocity(distance, time)
% CALCULATEVELOCITY Calculate average velocity.
% VELOCITY = CALCULATEVELOCITY(DISTANCE,TIME) calculates
% average velocity from distance and time.
%
% DISTANCE is measured in metres.
% TIME is measured in seconds.
% VELOCITY is returned in metres per second.
velocity = distance ./ time;
end
Someone using this function does not need to open the implementation just to figure out what the inputs mean.
That is exactly what useful documentation should accomplish.
Use %% to Organize Long MATLAB Scripts
If your MATLAB file is getting long, normal comments are not always enough. This is where sections become useful.
MATLAB uses two percent signs to create a section:
%% Load Data
You can use sections to divide a script into logical stages.
For example:
%% Load Data
data = readmatrix("experiment.csv");
%% Clean Data
data = rmmissing(data);
%% Calculate Results
averageValue = mean(data);
%% Display Results
plot(data);
This is especially handy when working in the MATLAB Editor because sections can be run separately.
For a larger project, you might organize your script into sections such as:
- Load data
Information in analog or digital form that can be transmitted or processed. Read Full Definition - Clean data
- Define parameters
- Run calculations
- Generate figures
- Save results
I would avoid creating a section for every tiny calculation, though. If a script contains ten sections for ten simple lines of code, the structure can become more distracting than helpful.
When Inline Comments Make Sense
An inline comment appears on the same line as the code.
threshold = 0.05; % Significance level
This is useful when the explanation is short.
Constants are a good example:
g = 9.81; % Gravitational acceleration in m/s^2
So are limits or parameters whose meaning might not be obvious:
maxIter = 1000; % Maximum number of iterations
What I would avoid is commenting every single statement:
x = 10; % Set x to 10
y = 20; % Set y to 20
z = x + y; % Add x and y
result = z/2; % Divide z by 2
There is nothing wrong with these comments technically. They are simply unnecessary.
A reader who understands MATLAB can already see what each line does.
Instead, explain the overall purpose:
% Calculate the midpoint between the two measured values.
x = 10;
y = 20;
result = (x + y) / 2;
That keeps the code cleaner while still giving the reader useful information.
How to Use Block Comments
Sometimes one line is not enough to explain a complicated part of a program. MATLAB supports block comments using %{ and %}.
For example:
%{
This section uses an iterative method to estimate
the solution. The calculation continues until
the error falls below the specified tolerance.
%}
Block comments can be useful for explaining a complicated algorithm, a temporary experiment, or a larger piece of logic.
However, I would not use a huge block comment when a few short comments would be clearer. Long walls of text inside a .m file can make the actual code difficult to find.
The same rule applies here: write enough to help the reader, but do not bury the program under documentation.
Keep Comments Close to the Code They Explain
A comment should normally sit close to the statement or block it describes.
For example:
if temperature > threshold
% Record measurements above the safety threshold.
highValues(end + 1) = temperature;
end
This is easier to follow than putting the explanation several lines above the if statement.
Indentation matters too.
Prefer:
if temperature > threshold
% Record measurements above the safety threshold.
highValues(end + 1) = temperature;
end
rather than:
if temperature > threshold
% Record measurements above the safety threshold.
highValues(end + 1) = temperature;
end
The indentation makes it immediately clear which part of the program the comment belongs to.
Do Not Let Comments Become Outdated
One of the easiest mistakes to make is changing the code but forgetting to change the comment.
Imagine you originally wrote:
% Convert Fahrenheit to Celsius.
temperature = (temperature - 32) * 5/9;
Later, you change the calculation to something else but leave the old comment behind.
The program may work perfectly, but the documentation is now misleading.
That is why I treat comments as part of the code. Whenever I make a significant change, I check the nearby comments as well.
An outdated comment can cause more confusion than having no comment at all.
Keep Comments Short and Easy to Read
You do not need to write an essay every time you explain a calculation.
Instead of this:
% This calculation removes all of the measurements that are outside the accepted operating range before the statistical analysis is performed on the remaining measurements.
break it into something easier to scan:
% Remove measurements outside the accepted operating range
% before performing the statistical analysis.
Shorter comments are easier to read, especially when someone is trying to understand the code quickly.
MathWorks’ MATLAB Coding Guidelines recommend keeping code and comment lines within a reasonable width, with a maximum of 120 characters in the current guidelines.
Commenting Out MATLAB Code
Comments are also commonly used during development when you want to temporarily prevent a line from running.
For example:
% plot(time, temperature);
For several lines, you can use a block comment:
%{
plot(time, temperature);
title("Temperature");
xlabel("Time");
ylabel("Temperature");
%}
This can be convenient while testing different versions of a program.
But there is a limit to how useful this approach is.
If you have an old section of code that has been commented out for months, it is probably time to remove it. Keeping large amounts of dead code inside a MATLAB script makes the file harder to understand.
If you need to preserve an older version, a version-control system such as Git is generally a better solution.
Comments and MATLAB Live Scripts
If you are working with a MATLAB Live Script, you have more options than ordinary comments.
Live Scripts allow you to combine MATLAB code with formatted text, equations, images, and output. This makes them particularly useful for laboratory work, tutorials, demonstrations, and coursework.
For example, instead of putting a long explanation inside a code comment, you can place a short piece of formatted text above the calculation and keep the code itself clean:
validData = data(~isnan(data));
averageResponse = mean(validData);
plot(validData);
The surrounding Live Script text can explain the purpose of the calculation, while the code remains focused on performing it.
This is often a better choice when the explanation is intended for a human reader rather than another programmer maintaining the source code.
A Simple Before-and-After Example
Here is an example of a MATLAB script that works but could be documented better:
% Load data
data = readmatrix("temperature.csv");
% Get first column
time = data(:,1);
% Get second column
temperature = data(:,2);
% Find mean
meanTemperature = mean(temperature);
% Plot temperature
plot(time, temperature);
There is nothing technically wrong with this code. The problem is that most of the comments simply repeat the commands.
I would make it something like this:
%% Analyze Temperature Measurements
% Load measurements collected during the experiment.
data = readmatrix("temperature.csv");
% Separate time and temperature for analysis.
time = data(:,1);
temperature = data(:,2);
% Calculate the mean temperature for comparison with the model.
meanTemperature = mean(temperature);
%% Visualize Results
% Show how temperature changes during the experiment.
plot(time, temperature);
xlabel("Time (s)");
ylabel("Temperature (°C)");
title("Measured Temperature");
The second version gives the reader more information without adding a comment to every line.
It also uses sections to make the overall structure easier to understand.
That is generally what I want from comments: more context, less repetition.
Common MATLAB Commenting Mistakes to Avoid
When reviewing your MATLAB file, watch out for these common problems:
- Explaining obvious code: Avoid comments that simply translate a MATLAB statement into English.
- Commenting every line: Too many comments can make a program harder to scan.
- Ignoring indentation: Keep comments aligned with the code they describe.
- Forgetting units: Include units when they are important to understanding a value.
- Leaving old comments behind: Update comments when you change the implementation.
- Writing unnecessarily long explanations: Break complicated ideas into smaller pieces.
- Using inconsistent terminology: Use the same names and descriptions throughout the file.
- Keeping old code commented out indefinitely: Remove obsolete code when you no longer need it.
- Ignoring function documentation: Reusable functions should explain their inputs and outputs.
- Overusing sections:
%%is useful for organizing large scripts, but too many sections can make the structure confusing.
A Practical Way to Comment Your MATLAB Code
If you are not sure whether a particular line needs a comment, try this simple process.
1. Look at the purpose of the code
Ask yourself what the surrounding block is supposed to accomplish.
If that purpose is not obvious, add a short explanation.
2. Look for decisions
Did you choose a particular value, threshold, equation, approximation, or method for a reason?
If another person might reasonably ask “Why this value?”, that is a good place for a comment.
3. Check function inputs and outputs
For functions, make sure someone can understand how to call the function without reading the implementation.
4. Remove comments that add no information
Read each comment and then look at the code underneath it.
If the code already tells the entire story, you probably do not need the comment.
5. Review comments when you edit the code
This final step is easy to forget.
After changing an algorithm, check the comments around it. Make sure they still describe what the program actually does.
If you’re preparing MATLAB coursework and need help understanding how your code should be structured or documented, resources focused on matlab assignment writing can also be useful as a supplementary reference.
Final MATLAB Commenting Checklist
Before submitting or sharing your MATLAB program, take a minute to check the following:
- Does each important section have a clear purpose?
- Do my comments explain why rather than simply what?
- Are functions properly documented?
- Are important units and assumptions clear?
- Are comments placed near the code they describe?
- Is the indentation consistent?
- Have I removed unnecessary comments?
- Are the comments short enough to read comfortably?
- Are the comments still accurate after my latest changes?
- Could another MATLAB user understand the program without having to ask me what it does?
If you can answer yes to most of these questions, your commenting is probably on the right track.
Good MATLAB comments are not about filling your .m file with text. They are about making the important parts of your code easier to understand.
Use % for ordinary explanations, %% to organize larger scripts, block comments when a longer explanation is genuinely necessary, and function help text when you are documenting reusable code.
Most importantly, write comments for the person who will read the code later including yourself. A useful comment can save minutes of confusion when you return to a project after a long break, and that is usually a much better measure of good documentation than the number of comments in the file.