Add All Functions and Classes Under Subfolders into MATLAB Search Path — addpath(genpath(folderName))

Nov. 24, 2025 in Buffalo, United States • Updated Nov. 28, 2025

When programming in MATLAB, to facilitate organization, sometimes we may put some functions or classes under folders or some subfolders. And at this time, in order to use these functions or classes in the scripts of current folder, i.e., pwd, we need to use addpath function1 to add them into the search path. However, a single addpath function can’t import functions under subfolders. For example, here I new a folders folder in the current folder, and under this path, new three subfolders folder 1, folder 2, and folder 3. In which, I define a simple function helperAdd in folders/folder 3:

1
2
3
function c = helperAdd(a, b)
c = a+b;
end

Right now, the whole structure looks like this:

image-20251126145745024

Then, at this time, in the script.m file of current folder, I try to use addpath('folders') to import all functions under folders such that I can call helperAdd:

1
2
3
4
5
clc, clear, close all

addpath('folders')

c = helperAdd(1, 2)

but an error occurs:

1
2
3
4
5
6
helperAdd is not found in the current folder or on the MATLAB path, but exists in:
    C:\Users\admin\Desktop\draft\test genpath\folders\folder 3

Change the MATLAB current folder or add its folder to the MATLAB path.
Error in script (line 5)
c = helperAdd(1, 2) 

MATLAB says that it can find the helperAdd, but can’t call it since now helperAdd is still not in the search path.

To solve this problem, we need to use another function genpath2, i.e.,

1
2
3
4
5
clc, clear, close all

addpath(genpath('folders'))

c = helperAdd(1, 2)

then we’ll get a right output:

1
2
c =
     3

The genpath function is to2:

p = genpath(folderName) returns a character vector containing a search path that includes folderName and multiple levels of subfolders below folderName. p does not include folders named private, folders that begin with the @ character (class folders), folders that begin with the + character (namespace folders), folders named resources, or subfolders within any of these.

Like in this case, p = genpath('folders') will produce a results:

1
2
p =
    'folders;folders\folder 1;folders\folder 2;folders\folder 3;'

then the outer addpath function thereby could add all subfolder into the search path.


References