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

classclass methodclassdefffunction nameMATLABmethod nameobjectobjectoriented programmingoop

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)

Best Answer

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};