开发者

Do MATLAB functions know which directory they are defined in? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Find location of current m-file in Matlab

I would like to write an m-file that will display the directory the function is defined in.

For instance if the function foo.m is placed in the directories c:\bar and c:\foo (full path to the file is then either c:\bar\foo.m or c:\foo\foo.m), neither of which is intially on the MATLAB path, this sequence of commands

addpath("c:\bar");
foo

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

while

addpath("c:\foo");
foo

would produce the result I am located in directory c:\foo

开发者_StackOverflowHow can I write such a function?


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜