Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish between scripts and functions programmatically

Given a file name, how can I programmatically distinguish between scripts and functions in MATLAB?

If I attempt to pass an argument to a script, I get Attempt to execute SCRIPT somescript as a function:. Is there a way to detect this without attempting to execute it?


Update: As @craq pointed out, shortly after this question was posted, there was an article about this on MATLAB Central: http://blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab-file-is-this/

like image 399
Szabolcs Avatar asked Apr 09 '13 18:04

Szabolcs


2 Answers

Didn't find a clean solution, but you can probably use try-catch (as @Ilya suggested) and nargin

EDIT - Use function to avoid some naming conflict; use exist to further classify the input (e.g. MEX-file)

function is_script = is_a_script( varargin )
% is_a_script( varargin ) returns one of the following:
%   1: if the input is a script
%   0: if the input is a function
%  -1: if the input is neither a function nor a script.

is_script = 0;
switch( exist(varargin{1}) )
    case 2
        % If the input is not a MEX or DLL or MDL or build-in or P-file or variable or class or folder,
        % then exist() returns 2
        try
            nargin(varargin{1});
        catch err
            % If nargin throws an error and the error message does not match the specific one for script, then the input is neither script nor function.
            if( strcmp( err.message, sprintf('%s is a script.',varargin{1}) ) )
                is_script = 1;
            else
                is_script = -1;
            end
        end
    case {3, 4, 5, 6} % MEX or DLL-file, MDL-file, Built-in, P-file
        % I am not familiar with DLL-file/MDL-file/P-file. I assume they are all considered as functions.
        is_script = 0;
    otherwise % Variable, Folder, Class, or other cases 
        is_script = -1;
end
like image 82
YYC Avatar answered Sep 21 '22 01:09

YYC


If you are willing to use semi-documented features, here is something to try:

function tf = isfunction(fName)
    t = mtree(fName, '-file');
    tf = strcmp(t.root.kind, 'FUNCTION');
end

This is the same function used in MATLAB Cody and Contests to measure code length.

like image 29
Amro Avatar answered Sep 19 '22 01:09

Amro