How to Use addpath function in MATLAB: Add Folders to Search Path Guide
Vectorized implementations, execution benchmarks, and step-by-step programming documentation.
Using the addpath Function in MATLAB
The addpath function adds folders to MATLAB's search path, allowing you to run scripts/functions from those locations without specifying full paths. MATLAB searches the path for .m files when you call a function.
Syntax
addpath(folderName1, folderName2, ..., '-begin' | '-end') % Default: '-begin' (top of path) addpath(..., '-frozen') % Disables change detection oldPath = addpath(...) % Returns path before addingStep-by-Step Guide
- Add a Single Folder: MATLAB
addpath('C:UsersYourNameDocumentsMATLABMyFolder') % Adds to top - Add Multiple Folders: MATLAB
addpath('folder1', 'folder2', '-end') % Adds to bottom - Add Folder + All Subfolders (use genpath): MATLAB
addpath(genpath('C:MyProject')) % Includes all subfolders - Make Permanent:
- Run savepath to save for future sessions.
- Or add addpath commands to startup.m (in matlabroot/toolbox/local).
- Remove Folders: MATLAB
rmpath('C:MyFolder') - View Current Path: MATLAB
path % Displays full pat
Examples
- Temporary Add for Testing: MATLAB
addpath('.utils'); % Relative to current directory myFunction(); % Now callable rmpath('.utils'); % Clean up - Project Setup Script:
projectRoot = pwd;MATLABaddpath(genpath(fullfile(projectRoot, 'src'))); addpath(genpath(fullfile(projectRoot, 'tools'))); savepath;
Tips & Best Practices
- Use full paths to avoid issues across machines/OS.
- genpath skips folders like @class, +package, private.
- Check if added: which myFunction (shows path if found).
- Common Error: "Undefined function" → Add the folder!
- GUI Alternative: Home tab → Set Path → Add Folder → Save.
- Why Use It? MATLAB only finds files in current folder or on path.
Need Expert Guidance with MATLAB or Simulink?
Our 500+ PhD engineers provide verified MATLAB code, custom Simulink models, and 1-on-1 tutoring with comprehensive code quality verification.