Search code examples
matlabfunction

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.


Solution

  • 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