How to get the name of the running function/method when executing a class method?

36 次查看(过去 30 天)
Hello everybody,
I have a class with several methods and I want to write my own log-file which tells me if the executed methods threw an error or not. I have a function to save a success-parameter, with a timestamp and the name of the executed method, but how do I get the name of the running method to pass it to the log-function?
I know that I could just type in the name of the method in the function call by hand for every method, but I'm hoping for a better solution.
classdef classname
methods
function test( obj )
write2log( 'test' ); % instead of 'test' there should be a function
% which returns the name of the current function/method
end
end
end
mfilename does not work because it will only give me the name of the m-file, which is the name of the whole class.
Thanks for your help,
Tom
(MATLAB version: Matlab R2016b)

采纳的回答

Ameer Hamza
Ameer Hamza 2018-4-25
You can use dbstack. It returns function call stack as a struct array. Since you want the name of the lastest function in the call stack, you will need to access the first element of the struct array as shown below
funCallStack = dbstack;
methodName = funCallStack(1).name;
functionName name will have a format like this: '(class_name).(method_name)', you can use strsplit() to seperate the method name
methodNameSeperate = strsplit(methodName, '.');
methodName = methodNameSeperate{end};
  5 个评论
Guillaume
Guillaume 2018-4-25
Personally, I'd just hardcode the function name in the write2log code, rather than use dbstack (which as Stephen pointed out will slow down the execution). But if you were to use dbstack you'd implement it like this:
classdef classname
methods
function test( obj )
write2log();
%....
end
end
end
function write2log
stack = dbstack(1, '-completenames'); %completenames optional. Use 1 to bypass write2log in the call stack
fprintf('%s: %s\n', datetime, stack(1).name);
end
Tom Wenk
Tom Wenk 2018-4-25
Thanks to all of you guys, I got it working for me! :)
Is there a big performance drop when I use this?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by