MATLAB 提供了一种获取类元数据信息的方法(使用meta
包),但这仅适用于 OOP 类而不是常规函数。
一个技巧是动态编写一个类定义,其中包含您要处理的函数的源代码,并让 MATLAB 处理源代码的解析(这可能会像您想象的那样棘手:函数定义行跨越多行,实际定义之前的注释等...)
因此,在您的案例中创建的临时文件如下所示:
classdef SomeTempClassName
methods
function [value, remain] = divide(left, right)
%# ...
end
end
end
然后可以将其传递meta.class.fromName
给解析元数据...
这是此 hack 的快速而肮脏的实现:
function [inputNames,outputNames] = getArgNames(functionFile)
%# get some random file name
fname = tempname;
[~,fname] = fileparts(fname);
%# read input function content as string
str = fileread(which(functionFile));
%# build a class containing that function source, and write it to file
fid = fopen([fname '.m'], 'w');
fprintf(fid, 'classdef %s; methods;\n %s\n end; end', fname, str);
fclose(fid);
%# terminating function definition with an end statement is not
%# always required, but now becomes required with classdef
missingEndErrMsg = 'An END might be missing, possibly matching CLASSDEF.';
c = checkcode([fname '.m']); %# run mlint code analyzer on file
if ismember(missingEndErrMsg,{c.message})
% append "end" keyword to class file
str = fileread([fname '.m']);
fid = fopen([fname '.m'], 'w');
fprintf(fid, '%s \n end', str);
fclose(fid);
end
%# refresh path to force MATLAB to detect new class
rehash
%# introspection (deal with cases of nested/sub-function)
m = meta.class.fromName(fname);
idx = find(ismember({m.MethodList.Name},functionFile));
inputNames = m.MethodList(idx).InputNames;
outputNames = m.MethodList(idx).OutputNames;
%# delete temp file when done
delete([fname '.m'])
end
并简单地运行为:
>> [in,out] = getArgNames('divide')
in =
'left'
'right'
out =
'value'
'remain'