I would like to be able to run a function from the directory where it is defined. Let's say this is my folder structure:
./matlab
./matlab/functions1
./matlab/functions2
and I have all directories in my MATLAB path, so I am able to call the functions that are in these directories.
Let's say my function "func" resides in 'matlab/functions1'. My function contains command
csvwrite('data.csv', data(:));
Now, if I call "func" from ./matlab, 'data.csv' gets created in ./matlab. If I call it from ./matlab/functions2, it will get created in that directory. But I would like for the function to write 'data.csv' always in the directory, where the function is defined (./matlab/functions1), no matter what my current directory is. How can I achieve that?
mfilename called from 'inside' a function returns the function path and name.
fullPath = mfilename('fullpath');
pathString = fileparts(fullPath);
dataPath = [ pathString filesep 'data.csv'];
csvwrite(dataPath, data(:));
In addition to what @zellus suggested, you can use functions
to get information on a specific function, regardless of any m file being executed at the same moment. You set the function of interest by giving functions
the function handle:
funInfo = functions(@func);
fullPath = funInfo.file;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With