是否可以检查给定的 Matlab 脚本是 运行 本身还是被另一个脚本调用?

Is it possible to check if a given Matlab script is run by itself or called by another script?

我有一个 Matlab 脚本 A,它可以单独 运行 也可以被另一个脚本调用。我想在脚本 A 中输入一个 if 语句来检查脚本是 运行 本身还是被另一个脚本调用。我该如何检查?

你应该看看 dbstack

dbstack displays the line numbers and file names of the function calls that led to the current breakpoint, listed in the order in which they were executed. The display lists the line number of the most recently executed function call (at which the current breakpoint occurred) first, followed by its calling function, which is followed by its calling function, and so on.

并且:

In addition to using dbstack while debugging, you can also use dbstack within a MATLAB code file outside the context of debugging. In this case, to get and analyze information about the current file stack. For example, to get the name of the calling file, use dbstack with an output argument within the file being called. For example:

st=dbstack;

以下是从 File Exchange 上发布的 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

此方法归功于 Eduard van der Zwan

您可以使用函数dbstack - Function call stack

让我们将其添加到脚本文件的开头,将其命名为 '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

添加第二个名为 'dbstack_caller_test' 的脚本来调用您的脚本:

run dbstack_test

现在,当您从控制台 运行 dbstack_test 或单击 MATLAB 编辑器中的绿色三角形时:

>> dbstack_test
Called from itself

当您从 dbstack_caller_test

调用 运行ning 时
>> dbstack_caller_test
Called from somewhere else: /home/matthias/MATLAB/dbstack_caller_test.m

当您在 MATLAB 的编辑器中使用 "run current section" (Ctrl+Return) 调用它时,您会得到

Warning: No function call stack available 

当然,您可以根据需要从调用堆栈使用哪个级别来修改代码。

如文档中所述:"In addition to using dbstack while debugging, you can also use dbstack within a MATLAB code file outside the context of debugging."