Mefitico
Mefitico

Reputation: 1116

Check if file is function or script in Matlab

For example, let's say I have a file named my_file.m, I'd like to do:

file_fullpath = ['path_to_file', filesep, 'my_file.m'];
is_function(file_fullpath)

I'd like a command (which is not is_function) that would determine if file_fullpath is a function or just a script and throw an error if the file does not exist or has some syntax problem that makes it undecidable. I'm guessing there should exist some built-in function to do it since Matlab correctly assigns different icons for functions and scripts in the navigator.

I could write a function to parse the file, looking for the appropriate keywords, but it would probably neither be simple, fast nor necessary.

Upvotes: 2

Views: 909

Answers (2)

atinjanki
atinjanki

Reputation: 492

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

file_fullpath = ['path_to_file', filesep, 'my_file.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: 0

Wolfie
Wolfie

Reputation: 30046

From this FileExchange submission: isfunction(), you can determine whether it is a function using a combination of:

% nargin gives the number of arguments which a function accepts, errors if not a func
nargin( ___ ); 
% If nargin didn't error, it could be a function file or function handle, so check
isa( ___, 'function_handle' ); 

More broadly, Jos has added multiple outputs to isfunction:

function ID = local_isfunction(FUNNAME)
try    
    nargin(FUNNAME) ; % nargin errors when FUNNAME is not a function
    ID = 1  + isa(FUNNAME, 'function_handle') ; % 1 for m-file, 2 for handle
catch ME
    % catch the error of nargin
    switch (ME.identifier)        
        case 'MATLAB:nargin:isScript'
            ID = -1 ; % script
        case 'MATLAB:narginout:notValidMfile'
            ID = -2 ; % probably another type of file, or it does not exist
        case 'MATLAB:narginout:functionDoesnotExist'
            ID = -3 ; % probably a handle, but not to a function
        case 'MATLAB:narginout:BadInput'
            ID = -4 ; % probably a variable or an array
        otherwise
            ID = 0 ; % unknown cause for error
    end
end

Upvotes: 1

Related Questions