Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Matlab script A that can either be run by itself or be called by another script. I want to enter an if statement in script A that checks if the script is run by itself or called by another script. How can I check this?

like image 352
Karlo Avatar asked Dec 24 '22 09:12

Karlo


1 Answers

You should check out 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.

And:

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;

The following is stolen from the iscaller function posted on the File Exchange.

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

Credit for this approach goes to Eduard van der Zwan.

like image 101
Stewie Griffin Avatar answered Apr 07 '23 10:04

Stewie Griffin