【问题标题】:Check if file is function or script in Matlab在 Matlab 中检查文件是函数还是脚本
【发布时间】:2020-09-04 20:04:33
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你可以add the folder with the file to the path然后尝试调用函数my_file(...)。如果它是一个函数,它应该运行。如果不是,它应该抛出一个错误。
  • 函数 M 文件的第一个非注释行以 function 开头。这就是您需要寻找的全部。丢弃以% 开头的行,并期望function

标签: matlab function


【解决方案1】:

从这个 FileExchange 提交: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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多