Question

I am looking for Matlab functionality to differentiate when script is run directly or from another script.

I build a script where I declare data to work on and I use this on other scripts and functions. When I run this script directly I would like to plot these data. When I call this script from another script I don't want to have all those plots.

In python I can build a function for plottings and call this function only when __name__=='__main__' I can't find how to do that in Matlab.

As example:

data.m

a = [1 2 3 4 5]
b = sin(a)
% plot only if run directly
figure
plot(a,b)

analysis.m

data
c = a.^2
figure
plot(c)

When I run analysis.m I want to have only plot(c) but not any other.

Was it helpful?

Solution 2

To complement @tashuhka answer (i.e using dbstack), and depending if you want to keep variables in the global scope, another solution is to turn your script into function and pass optional parameter to 'analysis.m'.

function [] = foo(doDebugPlot)
%[
    % Check params
    if (nargin < 1), doDebugPlot = true; end

    % Code
    ...

    % Debug
    if (~doDebugPlot), return; end

    plot(lala);
    plot(tutut); 
%]

OTHER TIPS

You can use ´dbstack´ [1] to see the function calls.

I don't know if this is possible in MATLAB. A workaround would be to use an if together with exist, like this:

analysis.m

run_data = 1;
data
c = a.^2
figure
plot(c)

data.m

a = [1 2 3 4 5]
b = sin(a)
% plot only if run directly
if ~exist('run_data','var')
   figure
   plot(a,b)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top