简体   繁体   English

MATLAB:使用inputParser和varargin

[英]MATLAB: Using inputParser with varargin

I have a function for which I would like to pass in arguments via varargin , and use the inputParser to ensure the inputs are sane. 我有一个函数,我想通过varargin传递参数,并使用inputParser确保输入是理智的。 Some arguments are required, and some are not. 有些论据是必需的,有些则不是。 Here is an example: 这是一个例子:

function myFunc(varargin)
    p = inputParser;
    p.addRequired(...
            'numStates', ...
                @(x) validateattributes(x, {'numeric'}, ...
                {'scalar', 'integer', 'positive'}));
        p.addRequired(...
            'numInps', ...
                @(x) validateattributes(x, {'numeric'}, ...
                {'scalar', 'integer', 'positive'}));
        p.addRequired(...
            'numOuts', ...
                @(x) validateattributes(x, {'numeric'}, ...
                {'scalar', 'integer', 'positive'}));
        p.addRequired(...
            'X0', ...
                @(x) validateattributes(x, {'numeric'}, ...
                {'vector'}));
        p.addOptional(...
            'freq', 10, ...
                @(x) validateattributes(x, {'numeric'}, ...
                {'scalar', 'integer', 'positive'}));
        p.addOptional(...
            'SimulinkVariables', struct(), ...
                @(x) isa(x, 'struct'));

    p.parse(varargin{:});

    %# do stuff with variables
end

I would like to be able to pass in arguments as follows; 我希望能够传递如下参数; it should not matter which pair gets passed in when, as long as the required ones are there. 只要有必要的那一对,那么哪一对传入就没关系。 So a sample call might be: 所以示例调用可能是:

myFunc('numStates', 4, 'numInps', 2, 'numOUts', 3, 'X0', [4;0]);

Apparently, this syntax is illegal; 显然,这种语法是非法的; parse() expects that the first arguments in it are the required values, but they should not be explicitly named, ie, as in: parse()期望其中的第一个参数是必需的值,但不应该显式命名,即:

function myFunc(numStates, numInps, numOuts, X0, varargin)
    ...
    p.parse(numStates, numInps, numOuts, X0, varargin{:});

end

Is there a simple way to make this do what I want, ie, the first function? 有没有一种简单的方法可以做到我想要的,即第一个功能? I guess the easiest thing to do is do something to reorder the elements of varargin and kick out the argument names, but that isn't terribly elegant. 我想最简单的事情是做一些事情来重新排序varargin的元素并踢出参数名称,但这并不是非常优雅。

The most elegant solution I can think of is to subclass inputParser . 我能想到的最优雅的解决方案是inputParser So you could do something like this (save as myInputParser.m): 所以你可以做这样的事情(另存为myInputParser.m):

classdef myInputParser < inputParser
    properties
        required = {};
    end

    methods
        function obj = myInputParser
            obj = obj@inputParser;
        end

        function addRequired(obj, argname, validator)
            obj.required = {obj.required{:}, argname};
            obj.addOptional(argname, [], validator);
        end

        function parse(obj, varargin)
            params_input = varargin(1:2:end);
            for i=1:length(obj.required)
                if isempty(strmatch(obj.required{i}, params_input))
                    error(sprintf('Required named parameter %s was not passed to function', obj.required{i}));
                end
            end
            parse@inputParser(obj, varargin{:});
        end

    end
end

Then change 然后改变

    p = inputParser;

to

    p = myInputParser;

and then your code will work as you want it to. 然后你的代码将按你的意愿工作。

Note that this might not handle all edge cases correctly, and I haven't tested it extensively, but it does work with your example use case. 请注意,这可能无法正确处理所有边缘情况,并且我没有对它进行过广泛的测试,但它确实适用于您的示例用例。

In InputParser you can add ParameterName - ParameterValue pairs only with addParamValue . 在InputParser中,您只能使用addParamValue添加ParameterName - ParameterValue对。 Those arguments are supposed to be optional. 这些论点应该是可选的。

As a workaround you can add all your parameters with addParamValue and use [] as default value for required arguments. 作为一种解决方法,您可以使用addParamValue添加所有参数,并使用[]作为必需参数的默认值。

Then you can do one of the following: 然后,您可以执行以下操作之一:

  • add 'nonempty' to attributes in validateattributes function for required arguments ( however in this case the error message will not say this is required arguments, but that it has to be non-empty ) 将“非空”添加到validateattributes函数中的属性以获取所需的参数( 但是在这种情况下,错误消息不会说这是必需的参数,但它必须是非空的
  • or add separate check (with if or assert ) that required arguments should be not-empty with your own error message. 或添加单独的检查(使用ifassert )所需的参数不应为空,并带有您自己的错误消息。

You are not limited to use [] . 您不限于使用[] The default can be any value not appropriate for a particular parameter and easy to check. 默认值可以是任何不适合特定参数的值,并且易于检查。

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

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