6

给定文件名,如何以编程方式区分 MATLAB 中的脚本和函数?

如果我尝试将参数传递给脚本,我会得到Attempt to execute SCRIPT somescript as a function:. 有没有办法在不尝试执行的情况下检测到它?


更新:正如@craq 指出的那样,在发布此问题后不久,MATLAB Central 上有一篇关于此的文章:http: //blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab -文件是这个/

4

3 回答 3

9

没有找到干净的解决方案,但您可能可以使用try-catch(如@Ilya 建议的那样)和nargin

编辑-function用于避免一些命名冲突;用于exist进一步分类输入(例如 MEX 文件)

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
于 2013-04-09T19:52:32.800 回答
3

如果您愿意使用半文档化功能,可以尝试以下方法:

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

这与MATLAB CodyContests中用于测量代码长度的函数相同。

于 2013-05-06T21:26:04.213 回答
2

这有点 hack,但是……true如果参数是函数,false如果不是函数,则返回一个函数。可能有一些例外情况不起作用 - 我期待着评论。

编辑- 捕捉函数在 mex 文件中的情况......

function b = isFunction(fName)
% tries to determine whether the entity called 'fName'
% is a function or a script
% by looking at the file, and seeing if the first line starts with 
% the key word "function"
try
    w = which(fName);
    % test for mex file:
    mx = regexp(w, [mexext '$']);
    if numel(mx)>0, b = true; return; end

    % the correct thing to do... as shown by YYC
    % if nargin(fName) >=0, b = true; return; end

    % my original alternative:
    fid = fopen(w,'r'); % open read only
    while(~feof(fid))
        l = fgetl(fid);
        % strip everything after comment
        f = strtok(l, '%');
        g = strtok(f, ' ');
        if strcmpi(g, 'function'), b=true; break; end
        if strlen(g)>0, b=false; break; end
    end
    fclose(fid);
catch
    fprintf(1, '%s not found!\n');
    b = false;
end
于 2013-04-09T19:53:02.973 回答