Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control where the function is run in MATLAB?

Tags:

matlab

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?

like image 467
Grega Kešpret Avatar asked Jan 20 '23 14:01

Grega Kešpret


2 Answers

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(:));
like image 145
zellus Avatar answered Feb 04 '23 22:02

zellus


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;
like image 21
Itamar Katz Avatar answered Feb 04 '23 20:02

Itamar Katz