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 Cody and Contestsでコード長を測定するために使用される関数と同じです。

于 2013-05-06T21:26:04.213 に答える
2

これはちょっとしたハックですが...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 に答える