'Matlab paths and file handling with packages and class folders
So I have the following (simplified) project structure.
scripts/
client.m
src/
+estimators/
@estimator1/
3party/
shell_script.sh
estimator1.m
Basically, what I try to do is, calling estimator1.m
from client.m
. This is working very well, no issues. However, from within estimator1.m
I try to call shell_script.sh
. The problem, relative paths do not work since it is always looking from the path client.m
is called.
What I tried from estimator1.m
is:
pathToScript = fullfile('3Party','shell_script');
system(pathToScript);
I would really like to avoid absolute paths since I'd like this package to be used by others as well. So hardcoding paths to my home directory is not good.
Solution 1:[1]
Use mfilename('fullpath')
to get the full path of the currently executing file. Use fileparts
to get just the directory part. Putting it together,
scriptdir = fullfile (fileparts(mfilename('fullpath')), '3Party');
Solution 2:[2]
Here is an additional answer to the one by @Edric. My second issue was that I wanted to implement the feature in the parent class since it is a functionality used by all child classes. The proposed answer is perfect when you have the function implemented in the class itself. However:
scriptdir = fullfile (fileparts(mfilename('fullpath')));
would always return the location of my parent class. So I implemented following in the parent class to retrieve the correct location in child classes:
function classdir= getClassDir(obj)
[classdir, ~, ~] = fileparts(which(class(obj)));
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Edric |
Solution 2 | Zeitproblem |