简体   繁体   English

使用inputParser类验证默认参数

[英]Validation of default parameters with `inputParser` class

The inputParser class in Matlab is very useful to synthetically check arguments passed by users when calling some function. Matlab中的inputParser类对于在调用某些函数时综合检查用户传递的参数非常有用。 For instance: 例如:

function [] = TestValidation(varargin)
%[
    p = inputParser();
    p.addParameter('Toto', 'Hello', @isnumeric);

    p.parse(varargin{:});
%]
end

Will raise an error if user attempt to assign a non numeric value to the parameter Toto (eg TestValidation('Toto', 'Hello') ==> raises an error because Hello is not a numeric). 如果用户尝试为参数Toto分配非数字值,则会引发错误(例如TestValidation('Toto', 'Hello') ==>会引发错误,因为Hello不是数字)。

Anyhow calling above function without parameters (ie TestValidation() ), there is no error raised even if default value for Toto is a string (ie Hello ). 无论如何,在没有参数的情况下调用上述函数(即TestValidation() ),即使Toto默认值是字符串(即Hello ),也不会引发错误。

Is there a simple way to force inputParser to validate also for default values or can it be done only manually and a posteriori ? 是否有一种简单的方法可以强制inputParser 对默认值进行验证,或者可以仅通过手动操作和后验方法来完成?

It's a class, create a subclass which implements the functionality you want: 这是一个类,创建一个实现所需功能的子类:

classdef myInputParser<inputParser
    methods
        function addParamValue(obj,name,default,fcn,varargin)
            assert(fcn(default));
            addParamValue@inputParser(obj,name,default,fcn,varargin{:});
        end
    end 
end

.

>> p = myInputParser();
>> p.addParamValue('Toto', 'Hello', @isnumeric);
Error using myInputParser/addParamValue
(line 4)
Assertion failed.

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

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