getting function name within that function run or currently running function
30 次查看(过去 30 天)
显示 更早的评论
I wish to save my output files in the name of the function that is producing those results. As I change versions of functions and their names very frequently, and forget changing output folder name each time. This makes it very difficult to trace the function versions that produced those results. If I can somehow get the function name automatically inside the function itself using some function and pass that string to output folder name that would help me solve my issue. Is there any function which can be used for this? I saw mfilename function (<http://www.mathworks.in/help/matlab/ref/mfilename.html>) but didn't understand how to use it. I got a blank string on using mfilename. Please see if anyone can help.
2 个评论
Daniel Shub
2013-5-31
The mfilename function is what you probably want. If that is not working you could write a wrapper around dbstack.
采纳的回答
Vandita
2013-6-5
1 个评论
Jan
2013-6-5
编辑:Jan
2013-6-5
I do not understand your solution. mfilename does not accept a "path where the function resides" as input, but I assume you mean
folder_name = fileparts(mfilename('fullpath'));
Starting the mkdir command through EVAL is an ugly and susceptible construction. Better run the command directly and avoid EVAL completely:
mkdir(folder_name)
Avoiding EVAL is a good idea in general, because there is always a better solution (except for 2 or three very rare and strange exceptions, which have been found by some Matlab cracks in this forum).
But finally there is no reason to create this folder, because it must be existing already - otherwise it could not be the parentfolder of the current M-file.
更多回答(2 个)
per isakson
2013-5-31
Try
>> cssm
which returns
ans =
cssm/cssm2
where
function name = cssm()
name = cssm1();
function name = cssm1()
name = cssm2();
end
function name = cssm2()
name = current_function('-full');
end
end
and where
function caller_name = current_function( inarg )
%
% See also: mfilename
dbk = dbstack( 1 );
if isempty( dbk )
str = 'base';
else
str = dbk(1).name;
end
ixf = find( str == '.', 1, 'first' );
if isempty( ixf ) || ( nargin==1 && strcmp( inarg, '-full' ) )
caller_name = str;
else
caller_name = str( ixf+1 : end );
end
end
0 个评论
Kaustubha Govind
2013-5-31
mfilename seems like the right solution for your case. Are you testing it by calling it from the MATLAB command window by any chance? You need to call it from a function. For example:
function mytest
fprintf('Currently executing %s\n', mfilename);
end
>> mytest
Currently executing mytest
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!