Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in test for whether a string (or handle) refers to a script?

Tags:

matlab

The function below is a homegrown hack to detect whether its argument refers to a script or not

function yesno = is_script(string_or_handle)
    try
        nargin(string_or_handle);
        yesno = false;
    catch me
        if ~strcmp(me.identifier, 'MATLAB:nargin:isScript')
            rethrow(me);
        end
        yesno = true;
    end
end

Such hacks are hard to maintain. (This one will break, for example, whenever MathWorks decides to change the class of exception identifier that nargin throws when it gets a script as input.)

Does MATLAB already have a built-in function to do this?

like image 642
kjo Avatar asked Jan 30 '16 00:01

kjo


1 Answers

You could modify your hack to be less prune to future "breaking" by running the try-catch block only for function handles. In this case you would know that if an error if thrown, then the input handle is a script (no need to investigate error details; hence no sensitivity to exception identifiers).

function yesno = is_script(string_or_handle)
    yesno = false;
    if isa(string_or_handle,'function_handle') || ... 
        exist(string_or_handle,'file') == 2
        try
            nargin(string_or_handle);
        catch me
            yesno = true;
        end  
    end
end
like image 109
dfrib Avatar answered Oct 23 '22 14:10

dfrib