Polyglot
Languages MATLAB modules
MATLAB § modules

Toolboxes and the path

MATLAB has no module system in the strict sense — no import keyword, no required file-level declaration of dependencies, no formal package manifest. Code is organised by files on the search path (each file is a unit of code) and, optionally, by package folders (folders whose name begins with +). Reusable libraries are distributed as toolboxes — collections of .m and .mlx files, classes, and resources packaged as a .mltbx file. The mechanism is informal but workable; the Path, the Add-Ons explorer, and (since R2017b) the project feature provide tooling around it.

The search path

MATLAB resolves an unqualified function name by walking an ordered list of directories called the search path. The current directory is always first; the standard-library directories are at the end. The path is configured with path, addpath, rmpath, and savepath:

addpath("/Users/me/code/utils")              % prepend
addpath("/Users/me/code/utils", '-end')      % append
rmpath("/Users/me/code/utils")
path                                          % display the entire path
which sin                                     % find the file backing sin

The default path is initialised at startup from pathdef.m, which the Set Path dialog edits and persists. Code in a directory that is not on the path is not callable; this is the principal unfindable function error new users encounter.

Files, functions, scripts

The smallest unit of code is the .m file. As covered in Workspace and scope, a file is either:

  • A function filefunction-keyword leading line, file name matching the function name, the function callable from anywhere on the path.
  • A script file — no leading function, the body of the script executes in the base workspace when the file name is typed at the prompt.

A function file may also contain local functions after the principal function; these are visible only inside the file. A script may contain local functions since R2016b.

The file system is the module system: each file is a unit, and the path mechanism is the only resolver.

Packages: the + folder

A folder whose name begins with + is a package. Files and classes inside it are namespaced by the package name:

~/code/+stats/
    mean2.m
    variance.m
    +tests/
        runAll.m

The function mean2.m is referred to as stats.mean2; the nested function runAll.m is stats.tests.runAll. The package folder itself need not be on the path; only the parent of the top-level package folder is added:

addpath("/Users/me/code")        % NOT addpath("/Users/me/code/+stats")
stats.mean2(rand(3, 3))           % the qualified call

Inside a function in the package, the import keyword may bring names into scope:

function y = doStuff(x)
    import stats.mean2 stats.variance
    y = mean2(x) - variance(x);
end

The import form is function-scoped — it applies only to the function in which it is written; there is no file-level import. Wildcard imports — import stats.* — are also supported.

Packages provide namespacing that the flat function namespace otherwise lacks. They are the recommended way to organise non-trivial codebases, especially those that may share names with the standard library or with other packages.

Class folders

A folder named @MyClass defines a class; the file @MyClass/MyClass.m contains the classdef block, and other .m files in the folder are methods of the class. The mechanism predates the classdef keyword by a decade and remains in widespread use:

~/code/@Polynomial/
    Polynomial.m       (classdef block; constructor; properties)
    plus.m             (method: implements Polynomial + Polynomial)
    times.m            (method)
    plot.m             (method)

In new code, the entire class is usually written in a single classdef file in a regular folder; the @-folder form is preferred when the class becomes large enough that splitting methods across files improves readability.

Toolboxes

A toolbox is a reusable, packaged library — the MATLAB analogue of a Python package or an npm module. A toolbox is structured as a folder containing functions, classes, examples, tests, and an info file; the Toolbox Packaging dialog (in the Add-Ons menu) writes the folder to a single .mltbx file that installs onto a user’s MATLAB.

The official toolboxes — those sold by The MathWorks — are installed through the Add-Ons explorer; community toolboxes are distributed through the File Exchange (mathworks.com/matlabcentral/fileexchange) and increasingly through GitHub. The addons command lists installed add-ons:

addons('install', '/path/to/MyToolbox.mltbx')
addons('list')
addons('uninstall', 'MyToolbox')

A toolbox can declare required products (other toolboxes), an installation script that runs after install, and examples that appear in the Help Browser.

Projects

Since R2017b MATLAB has supported projects — a higher-level organising construct for code, paths, tests, dependencies, and version control. A project is created with File → New → Project; it manages:

  • The path (which folders are added when the project opens).
  • Source control integration (Git or SVN).
  • Shortcuts and startup scripts.
  • Required products and add-ons.
  • Project references — other projects this project depends on.
  • Test execution and reporting.

The project mechanism is the recommended way to organise codebases that are larger than a few files and that will be shared with collaborators.

Dependency analysis

The function matlab.codetools.requiredFilesAndProducts(filename) returns the transitive closure of files and toolboxes a piece of code depends on. The companion Dependency Analyzer (in the Apps menu) presents the same information graphically. The mechanism is the practical answer to “what do I need to ship?” and is the basis of the toolbox-packaging dialog’s automatic include-list.

[files, products] = matlab.codetools.requiredFilesAndProducts("analyse.m");
% files: cell of all .m files transitively called
% products: struct array of toolbox dependencies

A note on the absence of an import

A reader familiar with Python is sometimes confused by MATLAB’s lack of an import at the top of a file: how can the file know which standard-library functions are available? The answer is that the entire standard library is always available — it is on the path that MATLAB sets at startup — and that user code on the path is similarly always available. There is no need to import; the only reason import exists at all is to shorten the names within a function that uses packaged code.

The Octave alternative

For users without a MATLAB licence, GNU Octave (octave.org) is the closest open-source alternative. The two languages share most of their syntax and a substantial fraction of their standard library. Differences include the indexing-on-function-output corner (f(x)(1) works in Octave, fails to parse in MATLAB), the OOP system (Octave’s is similar but not identical to MCOS), and the toolbox ecosystem (Octave has many but not all of the MathWorks toolboxes’ equivalents, in varying states of completeness). Code intended to run on both is usually written in a conservative subset of MATLAB and tested under both runtimes.