Do the MATLAB functions know the directory in which they are defined?

Possible duplicate:
Find the location of the current m file in Matlab

I would like to write an m file that displays the directory in which the function is defined.

For example, if the function foo.m is placed in the directories c: \ bar and c: \ foo (the full path to the file is either c: \ bar \ foo.m or c: \ foo \ foo. M), none of which not inside MATLAB path, this sequence of commands

addpath("c:\bar"); foo 

will produce the result: I am located in the c: \ bar directory

a

 addpath("c:\foo"); foo 

will lead to a result. I am located in the c: \ foo directory

How can I write such a function?

+4
source share
2 answers

Are you looking for the mfilename function? The optional input argument fullpath returns the full path to the m file from which the function is called.

+6
source

Praetorian is correct. You may also be interested in the fileparts function. Below is the code that should do what you request.

 function foo fprintf('I am located in directory %s', fileparts(mfilename('fullpath'))) 
+2
source

All Articles