Coding Style and Idioms
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
Written against MATLAB R2026b. Style is the part of a language that the compiler does not check, and MATLAB is forgiving: it accepts length where numel was meant, a variable called i, a script that begins with clear all. This page collects the conventions that experienced MATLAB programmers apply, anchored on the one set that MathWorks publishes, and then the idioms and the pitfalls that the other pages of this section explain in detail. Examples that Octave 11.3.0 can run were run there and the captured output is labelled; the rest are labelled "not run here".
The MATLAB Coding Guidelines
MathWorks publishes recommended coding guidelines on GitHub at mathworks/MATLAB-Coding-Guidelines. The latest release is version 1.0.0, published 2025-09-17, and the repository’s table says to use version 1.0 with MATLAB R2025a and higher. The repository describes them as developed mainly for large teams that want regularity and consistency in a code base, and their use is optional. They are a starting point for your own local guidelines, not a standard that MATLAB enforces.
The guidelines distinguish two kinds of guideline:
| Type | Meaning |
|---|---|
Rule |
Must be followed to comply with the guidelines. A rule violation can be detected by the MATLAB Code Analyzer, which marks it in the Editor and in the Code Analyzer report, for most rules; some rules are "not currently detected". |
Best Practice |
A recommendation to improve code quality. Following it is optional; some best practices can be detected as rules by enabling a check in the Code Analyzer. |
Each release of the guidelines ships a codeAnalyzerConfiguration.json file with the Code Analyzer checks that detect the rule violations; the file is the machine-readable form of the document, and the way to apply the guidelines to a project. How to load a configuration, and what the Code Analyzer and codeIssues report, is on Code Analyzer and Code Quality. The repository also links a rule file for AI coding assistants so that generated MATLAB code follows the same standard.
The document has these parts (the headings of the 1.0.0 document): naming, statements and expressions, formatting, code comments, function authoring, class authoring and error handling. This page summarises the parts in its own words and does not reproduce the document, whose text belongs to MathWorks; read the original for the exact wording, motivations and examples of every rule.
Names
| Element | Guideline (version 1.0.0) | Example |
|---|---|---|
Variables |
Rule: lowerCamelCase for descriptive multi-word names; a leading uppercase letter is allowed for short names that follow mathematical convention, such as a matrix |
|
Functions |
Rule: lowerCamelCase or lowercase; prefer lowerCamelCase for several words |
|
Classes |
Rule: UpperCamelCase for classes defined in a namespace; for a class in the global namespace use the function-name rule |
|
Properties and events |
Rules: UpperCamelCase |
|
Name=Value argument names |
Best Practice: UpperCamelCase, as MATLAB’s own functions do |
|
Names in general |
Descriptive names that document the code; avoid shadowing a function or a variable that other code may need; limit the length of names of the programming interface |
The Code Analyzer checks named in the document for names include naming.variable.regularExpression, naming.function.casing, naming.property.casing and naming.event.casing, introduced in R2025a, which is why the guidelines target R2025a and later.
Layout and comments
-
Spaces, not tabs; four spaces per indentation level (rules; applied by the Editor’s default settings).
-
Lines of at most 120 characters, code and comments (a rule detected by the Code Analyzer check
LLMNC). Long expressions are split with...or, better, with intermediate variables. -
No spaces just inside parentheses, brackets or braces; spaces after commas and semicolons; spaces around assignment and relational operators (rules).
-
Blank lines around related blocks, local functions and method blocks.
-
Comments in the language of the team, with the help text (the H1 line and what follows) at the top of the file. See Help Text and Documenting Code.
Statements and functions
-
Avoid
globalvariables (Best Practice; the Code Analyzer checkGVMISflags a misuse) and take care withpersistentones. -
Do not compare floating-point values with
==or~=(Best Practice): use a tolerance, orisapprox(R2024b). -
Build and parse file names with
fullfile,filepartsandfilesep. -
Preallocate arrays instead of growing them in a loop (Best Practice; the Code Analyzer reports the growth as
AGROW, a check that dates from R2006b). -
Avoid
eval, and avoid the workspace and path functions in library code. -
End every function with
end(rule). Prefer value classes to handle classes unless the object has an identity that must be shared (Best Practice). -
At most six inputs to a function (rule); use name-value arguments for optional information, and validate arguments with an
argumentsblock. -
Use
try/catchwith the exception object, write informative error messages, and reset any changed state when an error occurs.
A function in the guidelines' style
The function below advances the heatflow temperature field by one explicit step. It follows the guidelines: lowerCamelCase names, four-space indentation, help text at the top, lines shorter than 120 characters, the array preallocated, end closing the function. Octave 11.3.0 ran it in a script file (Octave needs the leading 1; to define a function in a script; MATLAB does not).
1;
function T = stepFieldExplicit(T, alpha, dx, dt)
% Advance the temperature field by one explicit step.
lap = zeros(size(T));
lap(2:end-1,2:end-1) = (T(1:end-2,2:end-1) + T(3:end,2:end-1) ...
+ T(2:end-1,1:end-2) + T(2:end-1,3:end) - 4*T(2:end-1,2:end-1)) / dx^2;
T = T + dt*alpha*lap;
end
T = zeros(5,5); T(3,3) = 100;
T = stepFieldExplicit(T, 1.0, 1.0, 0.1);
disp(T(3,3))
disp(T(2,3))
Octave 11.3.0 output:
60 10
The centre cools from 100 to 60 and its neighbour warms from 0 to 10: the stencil conserves the total (60 plus four times 10 is 100). In MATLAB the same function would carry an arguments block (see Argument Validation), which Octave 11.3.0 does not support, so it is omitted here. In a project, the stability limit dt <= dx^2/(4*alpha) should be checked in the caller; the example uses dt = 0.1, which is well inside it for alpha = 1 and dx = 1.
Idioms
| Prefer | Instead of | Why |
|---|---|---|
|
|
|
|
|
says what is meant, works for any array |
|
|
the flag is accepted by the statistics functions of base MATLAB; the older form drops values by hand |
String arrays and double quotes ( |
Character arrays and |
|
An |
|
declares the contract once |
Function handles and |
|
no parsing at run time; see eval and Its Alternatives |
Arguments and return values |
|
no hidden coupling between functions |
|
|
|
Implicit expansion ( |
|
R2016b and later |
|
|
R2022b and later |
Preallocation ( |
Growing an array in a loop |
fewer reallocations; the |
|
loop variables called |
the loop variable hides the constant |
Most rows of that table are MATLAB-only and were not run, because Octave cannot run them: "omitmissing" is a MATLAB name-value form, and dictionary and arguments do not exist in Octave 11.3.0. Octave does reproduce length, numel, isempty, and the loop-growth and i points:
A = zeros(3,5);
disp(length(A))
disp(numel(A))
disp(isempty(zeros(0,3)))
v = [1 NaN 3];
disp(mean(v))
disp(mean(v(~isnan(v))))
z1 = 2 + 3*i
for i = 1:2
end
z2 = 2 + 3*i
z3 = 2 + 3*1i
Octave 11.3.0 output (the complex values display with Octave’s spacing; MATLAB’s layout differs):
5 15 1 NaN 2 z1 = 2 + 3i z2 = 8 z3 = 2 + 3i
length(A) is 5 for a 3-by-5 array and numel(A) is 15. mean of a vector with a NaN is NaN, and removing the NaN by hand gives 2, which the "omitmissing" flag does in MATLAB in one call. After the loop, i is 2 and 2 + 3*i is no longer complex: it is 8. Writing 1i is immune to this.
Common pitfalls
Each pitfall links to the page that explains it.
-
Loop variables shadow
iandj. Afterfor i = 1:n,iis no longer the imaginary unit. Write1i. See Syntax, Statements and Variables. -
'is the conjugate transpose. On complex dataA'conjugates;A.'only transposes. See Operators and Precedence. -
==on floating-point numbers.0.1 + 0.2 == 0.3is false. Compare with a tolerance or useisapprox. See Numeric Types and Floating Point. -
lengthversusnumel. See Matrices and Arrays. -
Growing arrays in loops. See Vectorization and Preallocation.
-
ifon an array is true only when every element is nonzero.if [1 1 0]takes the else branch. See Logical Type and Conditions. -
clear allin scripts. It clears more than variables. See Workspaces, Scope, Global and Persistent. -
charversusstringcomparison.'abc' == 'abd'compares elementwise and needs equal lengths, while"abc" == "abd"compares strings. See Strings and Character Arrays. -
Out-of-range or non-integer subscripts and
endin the wrong context. See Indexing. -
Missing data.
NaNpropagates throughsumandmean; use the"omitmissing"flag. See Missing Data. -
Implicit expansion that silently expands. A column plus a row gives a matrix, not an error. See Implicit Expansion and Compatible Sizes.
-
eval. See eval and Its Alternatives. -
Name clashes between functions and variables. See Function Precedence and Name Resolution.
-
Handle copies. Assigning a handle object copies the reference. See Value and Handle Classes.
-
Old forms from old books. See What’s New and Migrating Older Code.
Where older books differ
The older books predate the guidelines (2025), the Code Analyzer’s naming checks (R2025a) and most of the idioms above: they teach length, strcat on character vectors, bsxfun, nargchk, inputParser, eval for dynamic names and clear all at the top of every script, and name variables with underscores or capital letters at will. All of that still runs. The current practice is the right-hand columns above; the change is advisory, not enforced by the language.