how to get name of a function (within the function)

159 ビュー (過去 30 日間)
Mario Trevino
Mario Trevino 2013 年 7 月 2 日
回答済み: Luca Balbi 2019 年 5 月 6 日
Wise gentlemen: how do I get the name of a function within the function?

採用された回答

Shashank Prasanna
Shashank Prasanna 2013 年 7 月 3 日
Inside the function call the following:
st = dbstack;
namestr = st.name

その他の回答 (3 件)

Renwick Beattie
Renwick Beattie 2018 年 11 月 16 日
I realise I'm a bit late to the party, but I was trying to find a solution to this and realise others may have the same needs I do. Neither answer was quite what I wanted. I wanted to create a useful descriptor for where an error has occured so that in a deployed program I can trace back in the source code. Here's a crude testfunc to evaluate what each method returns
function testfunc()
display(['What we see the in parent function when using mfilename is:',mfilename])
st = dbstack;
display(['What we see the in parent function when using dbstack.name is:',st.name])
subfunc()
function subfunc()
display(['What we see inside the sub-function when using mfilename is:',mfilename]) %Jan
st = dbstack;
display(['What we see the in sub-function when using dbstack.name is:',st.name])%Shashank
display(['What we see the in sub-function when using dbstack(1).name is:',st(1).name]) %tweaked Shashank
Then run the following command
testfunc()
the command window returns:
What we see the in parent function when using mfilename is:testfunc
What we see the in parent function when using dbstack.name is:testfunc
What we see inside the sub-function when using mfilename is:testfunc
What we see the in sub-function when using dbstack.name is:subfunctestfunc
What we see the in sub-function when using dbstack(1).name is:subfunc
For my particular purpose the best solution is to return each element in the stack seperately, using the first entry db(1).name for the error dialogue title and for teh message body building a string from db(2:end).name with a useful seperator between

Luca Balbi
Luca Balbi 2019 年 5 月 6 日
mfilename is not an acceptable answer, as it returns the current file name, not the function's name. If you rely on mfilename inside a function and, for instance, this function gets incorporated as a method in a class, it will not return the expected output. Playing with dbstack results offers far more flexibility.

Jan
Jan 2013 年 7 月 3 日
This is a little more direct than dbstack:
nameStr = mfilename;

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by