如何在matlab中检索函数参数的名称?

Han*_*esh 19 reflection matlab

除了解析函数文件之外,有没有办法在matlab中获取函数的输入和输出参数的名称?

例如,给定以下函数文件:

divide.m

function [value, remain] = divide(left, right)
     value = floor(left / right);
     remain = left / right - value;
end
Run Code Online (Sandbox Code Playgroud)

从函数外部,我想得到一个输出参数数组,在这里:['value', 'remain']和输入参数类似:['left', 'right'].

在matlab中有一个简单的方法吗?Matlab通常似乎很好地支持反射.

编辑背景:

这样做的目的是在窗口中显示功能参数以供用户输入.我正在编写一种信号处理程序,对这些信号执行操作的函数存储在子文件夹中.我已经有一个列表和用户可以选择的每个函数的名称,但是某些函数需要额外的参数(例如,平滑函数可能会将窗口大小作为参数).

目前,我可以在程序将找到的子文件夹中添加一个新功能,用户可以选择它来执行操作.我缺少的是用户指定输入和输出参数,这里我遇到了障碍,因为我找不到函数的名称.

gno*_*ice 11

如果你的问题仅限于你想要解析文件中主函数的函数声明行的简单情况(即你不会处理本地函数,嵌套函数匿名函数),那么你可以提取使用一些标准字符串操作和正则表达式在文件中显示的输入和输出参数名称.函数声明行具有标准格式,但由于以下原因,您必须考虑一些变化:

(事实证明,块评论的核算是最棘手的部分......)

我已经整理了一个get_arg_names能够处理上述所有功能的功能.如果给它一个函数文件的路径,它将返回两个包含输入和输出参数字符串的单元格数组(如果没有,则返回空单元格数组).请注意,具有可变输入或输出列表的函数将简单地列出'varargin''varargout'分别列出变量名称.这是功能:

function [inputNames, outputNames] = get_arg_names(filePath)

    % Open the file:
    fid = fopen(filePath);

    % Skip leading comments and empty lines:
    defLine = '';
    while all(isspace(defLine))
        defLine = strip_comments(fgets(fid));
    end

    % Collect all lines if the definition is on multiple lines:
    index = strfind(defLine, '...');
    while ~isempty(index)
        defLine = [defLine(1:index-1) strip_comments(fgets(fid))];
        index = strfind(defLine, '...');
    end

    % Close the file:
    fclose(fid);

    % Create the regular expression to match:
    matchStr = '\s*function\s+';
    if any(defLine == '=')
        matchStr = strcat(matchStr, '\[?(?<outArgs>[\w, ]*)\]?\s*=\s*');
    end
    matchStr = strcat(matchStr, '\w+\s*\(?(?<inArgs>[\w, ]*)\)?');

    % Parse the definition line (case insensitive):
    argStruct = regexpi(defLine, matchStr, 'names');

    % Format the input argument names:
    if isfield(argStruct, 'inArgs') && ~isempty(argStruct.inArgs)
        inputNames = strtrim(textscan(argStruct.inArgs, '%s', ...
                                      'Delimiter', ','));
    else
        inputNames = {};
    end

    % Format the output argument names:
    if isfield(argStruct, 'outArgs') && ~isempty(argStruct.outArgs)
        outputNames = strtrim(textscan(argStruct.outArgs, '%s', ...
                                       'Delimiter', ','));
    else
        outputNames = {};
    end

% Nested functions:

    function str = strip_comments(str)
        if strcmp(strtrim(str), '%{')
            strip_comment_block;
            str = strip_comments(fgets(fid));
        else
            str = strtok([' ' str], '%');
        end
    end

    function strip_comment_block
        str = strtrim(fgets(fid));
        while ~strcmp(str, '%}')
            if strcmp(str, '%{')
                strip_comment_block;
            end
            str = strtrim(fgets(fid));
        end
    end

end
Run Code Online (Sandbox Code Playgroud)


Amr*_*mro 11

MATLAB提供了一种获取类元数据信息的方法(使用meta包),但这仅适用于OOP类而非常规函数.

一个技巧是动态编写一个类定义,其中包含您要处理的函数的源代码,并让MATLAB处理源代码的解析(这可能是您想象的棘手:函数定义行跨越多行,实际定义之前的注释等...)

因此,在您的案例中创建的临时文件将如下所示:

classdef SomeTempClassName
    methods
        function [value, remain] = divide(left, right)
            %# ...
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

然后可以将其传递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
Run Code Online (Sandbox Code Playgroud)

并简单地运行:

>> [in,out] = getArgNames('divide')
in = 
    'left'
    'right'
out = 
    'value'
    'remain'
Run Code Online (Sandbox Code Playgroud)