MATLAB Answers

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

57 views (last 30 days)
Tom Wenk
Tom Wenk on 25 Apr 2018
Commented: Tom Wenk on 25 Apr 2018
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)

Accepted Answer

Ameer Hamza
Ameer Hamza on 25 Apr 2018
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 Comments
Tom Wenk
Tom Wenk on 25 Apr 2018
Thanks to all of you guys, I got it working for me! :)
Is there a big performance drop when I use this?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!