MATLAB: How to access all .m files in different subfolders

directoryMATLAB

As my project grows, I came up with the idea to arrange the different functions into different folders. For example the solvers are in the "solver" folder, the utility functions in the "utilities" folder, etc. If I invoke my functions, the do not see each other because of being different folders. How can I eliminate this error? I would like to maintain this several-folders structure. Do I have to change the current directory all the time?
Thanks, Zoli

Best Answer

As part of my startup.m file, I start by calling the userpath function, then genpath and lastly, addpath. I’m not certain this is the most efficient method, since my startup.m file has evolved over the 15 or so years since MATLAB added the MATLAB directory to Documents, but it works.
Specifically:
MyPath = userpath;
MyDir = MyPath(1:strfind(MyPath,';')-1);
MyWorkDir = genpath(MyDir);
addpath(MyWorkDir, '-end');
EDIT — This works for Windows. No promises for Mac or Linux systems.