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 A

temperature, gibbsFreeEnergy

Functions

Rule: lowerCamelCase or lowercase; prefer lowerCamelCase for several words

inverseTransform, solarRadiation

Classes

Rule: UpperCamelCase for classes defined in a namespace; for a class in the global namespace use the function-name rule

shapes.Polynomial

Properties and events

Rules: UpperCamelCase

StartTime, RowSelected

Name=Value argument names

Best Practice: UpperCamelCase, as MATLAB’s own functions do

plot(x,y,LineWidth=2)

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 global variables (Best Practice; the Code Analyzer check GVMIS flags a misuse) and take care with persistent ones.

  • Do not compare floating-point values with == or ~= (Best Practice): use a tolerance, or isapprox (R2024b).

  • Build and parse file names with fullfile, fileparts and filesep.

  • 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 arguments block.

  • Use try/catch with 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

numel(A) and size(A,dim)

length(A)

length returns the largest dimension, so it changes meaning when an array is reshaped

isempty(A)

numel(A) == 0, length(A) == 0

says what is meant, works for any array

sum(x,"omitmissing"), mean(x,"omitmissing")

mean(x(~isnan(x)))

the flag is accepted by the statistics functions of base MATLAB; the older form drops values by hand

String arrays and double quotes ("text")

Character arrays and strcat on char vectors

string arrays hold many strings and concatenate with +

An arguments block

nargin tests, inputParser, varargin loops

declares the contract once

Function handles and feval with handles

eval with a string

no parsing at run time; see eval and Its Alternatives

Arguments and return values

global variables

no hidden coupling between functions

clearvars name or no clearing at all

clear all, clear classes

clear all removes more than variables (functions loaded in memory, global variables) and so slows the next run

Implicit expansion (A - v)

bsxfun, repmat for sizes only

R2016b and later

dictionary

containers.Map for new code

R2022b and later

Preallocation (zeros, createArray)

Growing an array in a loop

fewer reallocations; the AGROW check

i, j not used as variable names; 1i for the imaginary unit

loop variables called i or j

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.

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.