slayton
slayton

Reputation: 20319

How to determine if code is executing as a script or function?

Can you determine at runtime if the executed code is running as a function or a script? If yes, what is the recommended method?

Upvotes: 11

Views: 196

Answers (3)

atinjanki
atinjanki

Reputation: 492

You may use the following code to check if an m-file is a function or a script.

% Get the file's name that is currently being executed
file_fullpath = (mfilename("fullpath"))+".m";

t = mtree(file_fullpath ,'-file');
x = t.FileType

if(x.isequal("FunctionFile"))
    disp("It is a function!");
end
if(x.isequal("ScriptFile"))
    disp("It is a script!");
end

Upvotes: 1

Eitan T
Eitan T

Reputation: 32930

+1 for a very interesting question.

I can think of a way of determining that. Parse the executed m-file itself and check the first word in the first non-trivial non-comment line. If it's the function keyword, it's a function file. If it's not, it's a script. Here's a neat one-liner:

strcmp(textread([mfilename '.m'], '%s', 1, 'commentstyle', 'matlab'), 'function')

The resulting value should be 1 if it's a function file, and 0 if it's a script.

Keep in mind that this code needs to be run from the m-file in question, and not from a separate function file, of course. If you want to make a generic function out of that (i.e one that tests any m-file), just pass the desired file name string to textread, like so:

function y = isfunction(x)
    y = strcmp(textread([x '.m'], '%s', 1, 'commentstyle', 'matlab'), 'function')

To make this function more robust, you can also add error-handling code that verifies that the m-file actually exists before attempting to textread it.

Upvotes: 6

KlausCPH
KlausCPH

Reputation: 1835

There is another way. nargin(...) gives an error if it is called on a script. The following short function should therefore do what you are asking for:

function result = isFunction(functionHandle)
%
% functionHandle:   Can be a handle or string.
% result:           Returns true or false.

% Try nargin() to determine if handle is a script:
try    
    nargin(functionHandle);
    result = true;
catch exception
    % If exception is as below, it is a script.
    if (strcmp(exception.identifier, 'MATLAB:nargin:isScript'))    
        result = false;
    else
       % Else re-throw error:
       throw(exception);
    end
end

It might not be the most pretty way, but it works.

Regards

Upvotes: 7

Related Questions