Matlab Command Window Output Source [duplicate]

与世无争的帅哥 提交于 2019-12-25 17:14:32

问题


Possible Duplicate:
Find location of current m-file in Matlab

does anyone knows how to find which function is providing output to the command window in Maltab? I've written a code with many functions, I have output to the command window but I can't find which function is responsible for that. Thanks !


回答1:


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


来源:https://stackoverflow.com/questions/10890106/matlab-command-window-output-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!