11

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

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

6

+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.

Comments

1

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

1 Comment

Much nicer solution than the other hacks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.