How to control where a function runs in 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 the directories in my MATLAB path, so I can call the functions that are in these directories.

Say my function "func" is in "matlab / functions1". My function contains a command

 csvwrite('data.csv', data(:)); 

Now, if I call "func" from. / matlab, "data.csv" is created in. / matlab. If I call him out. / matlab / functions 2, it will be created in this directory. But I would like the function to always write "data.csv" to the directory where the function is defined (./matlab/functions1), regardless of what my current directory is. How can i achieve this?

+4
source share
2 answers

mfilename , called from inside, the function returns the path and name of the function.

 fullPath = mfilename('fullpath'); pathString = fileparts(fullPath); dataPath = [ pathString filesep 'data.csv']; csvwrite(dataPath, data(:)); 
+5
source

In addition to what @zellus suggested, you can use functions to get information about a particular function regardless of any m file that is executing at the same time. You define the function of interest by specifying the functions descriptor:

 funInfo = functions(@func); fullPath = funInfo.file; 
+4
source

Source: https://habr.com/ru/post/1337897/


All Articles