How do I call a MATLAB function from another directory without adding the files to the path?

44 vues (au cours des 30 derniers jours)
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?

Réponse acceptée

MathWorks Support Team
MathWorks Support Team le 11 Sep 2023
Modifié(e) : MathWorks Support Team le 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.

Plus de réponses (0)

Catégories

En savoir plus sur Search Path dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by