【问题标题】:Input parser interdependent optional argument输入解析器相互依赖的可选参数
【发布时间】:2014-07-09 09:15:02
【问题描述】:

在下面的函数中,我尝试让 Pt 在可选输入参数上。 如果未指定 Pt,则需要计算其他可选参数(该部分有效)。 但是当我指定它时:

Alg(b,'circle','Pt',ones(150,1))

我收到以下错误:

'Pt' 不是一个可识别的参数。对于列表 有效的名称-值对参数,请参阅文档 对于这个函数。

函数代码:

function [ v ] = Alg( b,shape,varargin )

%%Parse inputs
p = inputParser;

addRequired(p,'b',@isnumeric);
expectedShapes = {'square','circle'};
addRequired(p,'shape',@(x) any(validatestring(x,expectedShapes)));

defaultIt = 42;
addParameter(p,'It',defaultIter,@isnumeric);

addParameter(p,'t',@isnumeric);
addParameter(p,'v',@isnumeric);

parse(p,b,shape,varargin{:})
b = p.Results.b;
shape = p.Results.shape;
It = p.Results.It;
t = p.Results.t;
v  = p.Results.v;

parse(p,b,shape,varargin{:})
defaultPoint = Alg_sq(b,Pt,It);
defaultPoint = Sub_Alg(defaultPoint,shape,t,v);
addParameter(p,'Pt',defaultPoint,@isnumeric);
Pt = p.Results.Pt;

%%Shape
switch shape
    case 'circle'
        v = Alg_crcl( b,Pt,It );

    case 'square'
        v = Alg_sq( b,Pt,It );
end
end

非常感谢您的帮助!

【问题讨论】:

    标签: matlab function arguments optional-parameters optional-arguments


    【解决方案1】:

    它出错是因为在您最初解析参数时没有将Pt 指定为有效的参数名称。你需要稍微重构一下代码,我会这样做:

    function v = Alg(b, shape, varargin)
    
        % define arguments
        p = inputParser;
        addRequired(p, 'b', @isnumeric);
        addRequired(p, 'shape', @(x) any(validatestring(x,{'square','circle'})));
        addParameter(p, 'It', 42, @isnumeric);
        addParameter(p, 't', @isnumeric);
        addParameter(p, 'v', @isnumeric);
        addParameter(p, 'Pt', [], @isnumeric);   % default for now is empty matrix
    
        % parse arguments
        parse(p, b, shape, varargin{:})
        b = p.Results.b;
        shape = p.Results.shape;
        It = p.Results.It;
        t = p.Results.t;
        v  = p.Results.v;
        Pt = p.Results.Pt;
        if isempty(Pt)
            % insert your logic to compute actual default point
            % you can use the other parsed parameters
            Pt = computeDefaultValue();
        end
    
        % rest of the code ...
    
    end
    

    【讨论】:

    • 您可能想添加检查 any(strcmp(p.UsingDefaults,'Pt')) 以防用户专门调用 Alg(b, 'circle', 'Pt',[])(以区别于 Alg(b, 'circle')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2021-08-25
    • 2023-01-07
    相关资源
    最近更新 更多