Kar*_*rlo 3 matlab if-statement call
我有一个Matlab脚本A,既可以自己运行,也可以被另一个脚本调用.我想if
在脚本A中输入一个语句,用于检查脚本是由自己运行还是由另一个脚本调用.我怎么检查这个?
你应该看看dbstack
.
dbstack
显示导致当前断点的函数调用的行号和文件名,按其执行顺序列出.显示屏首先列出最近执行的函数调用(当前断点发生时)的行号,然后是其调用函数,后跟其调用函数,依此类推.
和:
除了在调试时使用dbstack,您还可以在调试上下文之外的MATLAB代码文件中使用dbstack.在这种情况下,获取和分析有关当前文件堆栈的信息.例如,要获取调用文件的名称,请在调用的文件中使用带有输出参数的dbstack.例如:
st=dbstack;
以下内容是从文件交换中iscaller
发布的功能中窃取的.
function valOut=iscaller(varargin)
stack=dbstack;
%stack(1).name is this function
%stack(2).name is the called function
%stack(3).name is the caller function
if length(stack)>=3
callerFunction=stack(3).name;
else
callerFunction='';
end
if nargin==0
valOut=callerFunction;
elseif iscellstr(varargin)
valOut=ismember(callerFunction,varargin);
else
error('All input arguments must be a string.')
end
end
Run Code Online (Sandbox Code Playgroud)
您可以使用函数dbstack
-函数调用堆栈。
让我们将其添加到脚本文件的开头,将其命名为“dbstack_test.m”:
% beginning of script file
callstack = dbstack('-completenames');
if( isstruct( callstack ) && numel( callstack ) >= 1 )
callstack_mostrecent = callstack(end); % first function call is last
current_file = mfilename('fullpath'); % get name of current script file
current_file = [current_file '.m']; % add filename extension '.m'
if( strcmp( callstack_mostrecent.file, current_file ) )
display('Called from itself');
else
display( ['Called from somewhere else: ' callstack_mostrecent.file ] );
end
else
warning 'No function call stack available';
end
Run Code Online (Sandbox Code Playgroud)
添加第二个名为“dbstack_caller_test”的脚本来调用您的脚本:
run dbstack_test
Run Code Online (Sandbox Code Playgroud)
dbstack_test
现在,当您从控制台运行或单击 MATLAB 编辑器中的绿色三角形时:
>> dbstack_test
Called from itself
Run Code Online (Sandbox Code Playgroud)
当你调用它运行时dbstack_caller_test
>> dbstack_caller_test
Called from somewhere else: /home/matthias/MATLAB/dbstack_caller_test.m
Run Code Online (Sandbox Code Playgroud)
当您在 MATLAB 编辑器中使用“运行当前部分”(Ctrl+Return) 调用它时,您会得到
Warning: No function call stack available
Run Code Online (Sandbox Code Playgroud)
当然,您可以根据需要使用调用堆栈的级别来修改代码。
正如文档中已经提到的:“除了在调试时使用 dbstack 之外,您还可以在调试上下文之外的 MATLAB 代码文件中使用 dbstack。”