How do I call a MATLAB function from another directory without adding the files to the path?
조회 수: 45 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2023년 3월 23일
편집: MathWorks Support Team
2023년 9월 13일
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?
채택된 답변
MathWorks Support Team
2023년 9월 11일
편집: MathWorks Support Team
2023년 9월 13일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Search Path에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!