How do I call a MATLAB function from another directory without adding the files to the path?
47 views (last 30 days)
Show older comments
MathWorks Support Team
on 23 Mar 2023
Edited: MathWorks Support Team
on 13 Sep 2023
I have two MATLAB functions I would like to use. Let's call them "f.m" and "g.m". In addition, I have some data store in file "data.m" that is in a subfolder of the location of "g.m". Functions "f.m" and "g.m", and file "data.m" are all located in different folders outside of the MATLAB path.
I am calling "f" first, and then at some point in the execution of "f" I call "g". When "g" is called, it needs to access the data in "data". I am calling "f" from an external application, so I cannot use the GUI to add the files to the path. I want to do this without using the "addpath" or "genpath" functions. Is this even possible?
Accepted Answer
MathWorks Support Team
on 11 Sep 2023
Edited: MathWorks Support Team
on 13 Sep 2023
You can consider using the "cd" command. You can run this command during the execution of your script to change directories to the desired location of your function (and data). Here is an example description of a modification to "f":
% Get path to current directory so we can return back when done executing g.
loc_A = pwd;
% here goes all the lines of code of f before calling g.
{...}
% Before calling g, change directory to B, the folder where g lives.
cd(loc_B);
% Inside g, we can access the data in data.m since it is in a subfolder.
% That is, we don't need to add another command here. So, execute all of g.
{...}
% Now we are done with g, so return back to the location of f before finishing executing g.
cd(loc_A);
% We are back inside f, now inish the execution of f.
{...}
Please refer to the following documentation for more information on the 'cd' command:
Note that the "cd" command never adds the files to the path, so you are never affecting your "path" variables. Instead, MATLAB runs function based on what it can see. This workaround has been verified in versions R2021a and later.
0 Comments
More Answers (0)
See Also
Categories
Find more on Search Path in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!