如何在Matlab中检索函数参数的名称? [英] How do I retrieve the names of function parameters in matlab?

查看:413
本文介绍了如何在Matlab中检索函数参数的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Aside from parsing the function file, is there a way to get the names of the input and output arguments to a function in matlab?

例如,给定以下功能文件:

For example, given the following function file:

divide.m

function [value, remain] = divide(left, right)
     value = floor(left / right);
     remain = left / right - value;
end

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

From outside the function, I want to get an array of output arguments, here: ['value', 'remain'], and similarly for the input arguments: ['left', 'right'].

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

Is there an easy way to do this in matlab? Matlab usually seems to support reflection pretty well.

编辑背景:

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

The aim of this is to present the function parameters in a window for the user to enter. I'm writing a kind of signal processing program, and functions to perform operations on these signals are stored in a subfolder. I already have a list and the names of each function from which the user can select, but some functions require additional arguments (e.g. a smooth function might take window size as a parameter).

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

At the moment, I can add a new function to the subfolder which the program will find, and the user can select it to perform an operation. What I'm missing is for the user to specify the input and output parameters, and here I've hit the hurdle here in that I can't find the names of the functions.

推荐答案

如果您的问题仅限于要解析

If your problem is limited to the simple case where you want to parse the function declaration line of a primary function in a file (i.e. you won't be dealing with local functions, nested functions, or anonymous functions), then you can extract the input and output argument names as they appear in the file using some standard string operations and regular expressions. The function declaration line has a standard format, but you have to account for a few variations due to:

  • Varying amounts of white space or blank lines,
  • The presence of single-line or block comments, and
  • Having the declaration broken up on more than one line.

(事实证明,对块注释的解释是最棘手的部分...)

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

I've put together a function get_arg_names that will handle all the above. If you give it a path to the function file, it will return two cell arrays containing your input and output parameter strings (or empty cell arrays if there are none). Note that functions with variable input or output lists will simply list 'varargin' or 'varargout', respectively, for the variable names. Here's the function:

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

这篇关于如何在Matlab中检索函数参数的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆