If all output is printed by your own code, you can easily replace all fprintf
and disp
calls with your own function calls that optionally prefix all output with the function name.
Here's the code:
getfunctionname.m:
function [CurrentFunctionName, PreviousFunctionName] = getfunctionname()
CurrentFunctionName = '';
PreviousFunctionName = '';
MyStack = dbstack('-completenames');
if (length(MyStack) < 2)
error('Function getfunctionname.m cannot be called from MATLAB console.');
elseif (length(MyStack) == 2)
CurrentFunctionName = MyStack(2).name;
else
CurrentFunctionName = MyStack(2).name;
PreviousFunctionName = MyStack(3).name;
end
return
myprintf.m:
function myprintf(varargin)
global PrefixOutputWithFunctionName
if (PrefixOutputWithFunctionName)
[~, PreviousFunctionName] = getfunctionname;
fprintf('### %s.m:\n', PreviousFunctionName);
end
disp(sprintf(varargin{:}));
return
mydisp.m:
function mydisp(varargin)
global PrefixOutputWithFunctionName
if (PrefixOutputWithFunctionName)
[~, PreviousFunctionName] = getfunctionname;
fprintf('### %s.m:\n', PreviousFunctionName);
end
disp(varargin{:});
return
mainfunction.m:
function mainfunction()
global PrefixOutputWithFunctionName
% set PrefixOutputWithFunctionName to false to disable prefixing.
PrefixOutputWithFunctionName = true;
% the code goes here...
% example output.
myprintf('some text...\n some more text...');
return