Search Path, Startup and Files
|
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. The path session below was run in GNU Octave 11.3.0 in a throwaway container (the same functions exist there, but Octave prints which differently and keeps its own default path); everything about startup.m, pathdef.m, userpath, savepath and the desktop is checked against the R2026b documentation and labelled "not run here".
"Undefined function or variable" is the commonest first error in MATLAB, and the commonest cause is not a typo but a file that MATLAB cannot see. This page explains where MATLAB looks, how to widen or narrow that, and how to run code automatically when MATLAB starts and exits.
Where MATLAB looks for a file
When you use a name without a path, MATLAB resolves it with a precedence order (variables first, then files and functions). For files, it looks in the current folder and then on the search path, from the top down: "Functions in the current folder take precedence over functions with the same file name that reside anywhere on the search path." (MATLAB documentation: Files and Folders That MATLAB Accesses). The complete precedence order, including variables, imports, nested functions, class methods and packages, is on Function Precedence and Name Resolution.
To make a file you wrote accessible, you can do one of three things:
-
Change the current folder to the folder that holds it (
cd), or browse to it in the Files panel. -
Add its folder to the search path.
-
Store it in the
userpathfolder, which is already on the path.
pwd displays the current folder, cd folder changes it, and ls and dir list its contents.
pwd
cd(fullfile(userpath, "heatflow"))
ls
Not run here (the answers depend on your machine).
The startup folder
The startup folder is the current folder when MATLAB starts. By default on Windows and macOS, when you start MATLAB from its shortcut or application icon, it is the userpath folder. You can set the initial working folder in the General page of the Settings window, and the documentation advises against putting cd statements in startup.m for that purpose. On Linux you can assign userpath as the startup folder as well (see "Assign userpath as Startup Folder" in the documentation).
The search path
The search path (the path) is the subset of all folders in the file system that MATLAB searches to find files used with MathWorks products. The order matters: when files with the same name appear in several folders, MATLAB uses the one nearest the top of the path. By default the path contains:
-
the
userpathfolder, which is added first at startup and is the default place to store your own files; -
folders listed in the
MATLABPATHenvironment variable; -
the folders of MATLAB and the other installed MathWorks products, which are under
matlabroot/toolbox(runmatlabrootto see the root).
The default userpath is %USERPROFILE%\Documents\MATLAB on Windows, $HOME/Documents/MATLAB on macOS, and the same on Linux if $HOME/Documents exists (in MATLAB Online it is /users/youruserid). userpath returns it, userpath(newpath) sets it (immediately and for future sessions, removing the previous one from the path), userpath("reset") restores the platform default, and userpath("clear") removes it.
Special folders
Four kinds of folder cannot be put on the path explicitly: class folders (@name), namespace folders (+name; called "package" folders before R2024a), private folders and resources folders. MATLAB adds them to the path implicitly when their parent is on the path. So you add the folder that contains +heatflow, not +heatflow itself, and the files in a private folder are visible only to the files in its parent. Making a folder accessible does not make its subfolders accessible; add the ones you need. For namespaces and class folders see Namespaces and Class Folders.
Viewing and changing the path
| Function | What it does |
|---|---|
|
Displays the search path. |
|
Adds folders to the top of the path for the current session. A final argument |
|
Removes a folder from the path for the current session. |
|
Returns a character vector containing |
|
Saves the current path to a |
|
Opens the Set Path dialog to add, remove and reorder folders and save. |
|
Resets the path to its factory state. Use it to diagnose a path problem, not as routine. |
|
Refreshes the function and file-system caches, for when MATLAB does not see a file you just created or changed by other means. |
|
The separator in path strings ( |
This session builds a small folder with a function in a subfolder, adds it with genpath, calls the function, and removes it again. It is the Octave 11.3.0 run:
d = fullfile(tempdir, 'hf_demo');
mkdir(d); mkdir(fullfile(d, 'sub'));
fid = fopen(fullfile(d, 'sub', 'hfdemo_fn.m'), 'w');
fprintf(fid, 'function r = hfdemo_fn()\n r = 42;\nend\n');
fclose(fid);
exist('hfdemo_fn')
p = genpath(d);
addpath(p);
hfdemo_fn()
which hfdemo_fn
rmpath(p);
exist('hfdemo_fn')
Octave 11.3.0 output (the folder is shortened):
ans = 0
ans = 42
'hfdemo_fn' is a function from the file <tempdir>/hf_demo/sub/hfdemo_fn.m
ans = 0
The function is invisible (exist is 0) until its folder is on the path, callable afterwards, and invisible again after rmpath. genpath(d) returned d followed by the path separator and d/sub, which is why one addpath call was enough. Nothing was saved, so none of this affects a future session: that is the right default for a script that needs a folder temporarily.
Saving the path for future sessions
addpath changes only the current session. To keep a change, use savepath or the Set Path dialog (pathtool). Both write pathdef.m; the file in matlabroot/toolbox/local is the default, and the documentation notes that it is the one file in the installation that you may update. On a system where you cannot write there (a managed installation, or Windows with User Account Control) savepath folder/pathdef.m writes a copy to a folder of your own, and starting MATLAB from that folder uses it.
addpath(genpath(fullfile(userpath, "heatflow")))
savepath
Not run here, because it changes your installation. The heatflow folder is where the examples of this section live. In practice a startup.m that calls addpath, or a project (see below), is a better way to set up a working environment than a hand-edited global path.
which -all and shadowing
Two files with the same name in different folders produce a shadowed file: MATLAB uses the one nearest the top and ignores the other, sometimes with a warning. which name shows the one that wins; which name -all lists every one, including methods of classes and files in special folders:
which sum -all
which stablestep -all
Not run here (the list depends on your installation). A well-known case is saving a script as sum.m or plot.m: the script then shadows the built-in function everywhere it is on the path, and other code starts failing in strange ways. Rename it, and run rehash or clear functions if the old version is cached. The rules for choosing between a variable, a file, a built-in and a class method are on Function Precedence and Name Resolution.
Source: MATLAB documentation: which
Files and folders MATLAB uses
-
matlabrootholds the installation. Files for MathWorks products are inmatlabroot/toolbox. Do not store personal files there or change files or subfolders under it, exceptpathdef.m.dir(fullfile(matlabroot, 'toolbox'))lists the product folders. -
userpathis your working folder, on the path. -
prefdiris the settings folder, which stores settings, layout and command history (see Desktop and Command Window). -
tempdiris the system temporary folder, andfullfilebuilds a path with the right separator for the platform. -
For files in
@class folders and+namespace folders, make the parent folder accessible. -
To find all the files a program needs, run a dependency analysis on it, and put those folders on the path (the documentation points to the dependency analysis of a folder).
-
For performance, MATLAB caches information about the folders under
matlabrootacross sessions ("toolbox path caching").
Startup and shutdown files
At startup MATLAB runs the function matlabrc (in matlabroot/toolbox/local; reserved for MathWorks and system administrators of multiuser systems) and then, if there is one on the path, startup. When you exit, it calls finish if one exists. Both are looked up by name like any other file: MATLAB executes the first file on the search path with that name and an executable extension (.m, .mlx, .mlapp).
startup.m
Put a startup.m file in the userpath folder, which is on the path, and write there what you want predefined: physical constants, default graphics properties, a path setup. The documentation’s example sets the default colormap:
edit(fullfile(userpath, 'startup.m'))
and adds the statement set(0, 'DefaultFigureColormap', autumn(64)) to the file. For heatflow, a startup file can put the project on the path:
% startup.m - run when MATLAB starts
addpath(fullfile(userpath, "heatflow"));
format long
Not run here (startup files run only when MATLAB starts). Keep startup files short: everything in them runs on every start, a failing statement prints a warning at every start, and code that depends on startup.m does not run on a colleague’s machine, in continuous integration, or under matlab -batch. Do not use cd in startup.m; use the initial working folder setting instead. To find the file MATLAB is using, run which startup, and remove it with delete(fullfile(userpath, 'startup.m')).
Source: MATLAB documentation: startup
finish.m
MATLAB runs finish when you close the desktop window or type quit or exit. If finish raises an error, the quit is cancelled so that you can fix the file without losing your workspace. The documentation’s example saves the workspace to a MAT-file when MATLAB quits with the sample file finishsav.m. See Workspace Variables and MAT-Files.
% finish.m - run when MATLAB exits
fprintf("Goodbye from heatflow\n");
Not run here.
Startup options
The matlab command accepts startup options, such as -batch "statement" (run non-interactively and exit), -r "statement" (run interactively) and -singleCompThread. They are listed on Commonly Used Startup Options, and getenv("MATLABPATH") shows the environment variable that adds folders to the path.
Why a project manages the path better
A global path is a shared, mutable resource. Two projects that each define utils.m fight over it, and a path saved in pathdef.m follows you around. A project declares its own folders, and MATLAB puts them on the path when the project opens and removes them when it closes. Since R2026b the project definition is a TOML file. See Projects and Source Control. For new code, prefer namespaces (a +heatflow folder whose parent is on the path) to a big flat folder of functions with long prefixed names.
Pitfalls
-
Adding the folder of a
+namespaceor@classfolder instead of its parent. The parent is what goes on the path. -
addpath(genpath(pwd))in a script adds version-control folders and generated folders too. Add only the folders you want, or use a project. -
Calling
savepathafter experiments writes the experiments topathdef.mfor ever. -
A function that works only from one folder works because of the current folder, which has priority; call it from elsewhere to find out.
-
A new file is not seen. Check
which name, thenrehash. -
Order matters.
addpathputs the folder at the top; with"-end"at the bottom, below the built-in folders.
Where older books differ
Books for MATLAB 7 teach the Set Path dialog and matlabrc edits, and edit startup.m to cd to a work folder. Today the initial working folder is a setting, a startup.m goes in the userpath folder, and a project is the recommended way to manage a code base.