tomasz74
tomasz74

Reputation: 16661

Matlab functionality similar to python's __name__=='__main__'

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.

Upvotes: 3

Views: 1971

Answers (3)

CitizenInsane
CitizenInsane

Reputation: 4855

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); 
%]

Upvotes: 2

tashuhka
tashuhka

Reputation: 5126

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

Upvotes: 3

Stewie Griffin
Stewie Griffin

Reputation: 14939

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

Upvotes: 2

Related Questions