繁体   English   中英

在Matlab中检查文件是函数还是脚本

[英]Check if file is function or script in Matlab

例如,假设我有一个名为my_file.m的文件,我想做:

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

我想要一个命令(不是is_function )来确定file_fullpath是一个函数还是一个脚本,并在文件不存在或存在一些使其无法确定的语法问题时抛出错误。 我猜应该存在一些内置函数来做到这一点,因为 Matlab 正确地为导航器中的函数和脚本分配了不同的图标。

我可以编写一个函数来解析文件,寻找合适的关键字,但它可能既不简单,也不快速,也不是必需的。

从这个isfunction()提交: isfunction() ,您可以使用以下组合来确定它是否是一个函数:

% 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' ); 

更广泛地说, Josisfunction添加了多个输出:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM