输入解析器相互依存的可选参数 [英] Input parser interdependent optional argument

查看:125
本文介绍了输入解析器相互依存的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的函数,我试图让铂上可选的输入参数。
在未指定的Pt的情况下,它需要计算其它可选参数(即部分作品)。
但是,当我指定它:

In the following function, I tried to let Pt be on optional input parameter. In case Pt is not specified, it needs other optional parameters to be computed (that part works). But when I specify it:

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

我收到以下错误:

I get the following error:

铂是无法识别的参数。对的列表
  有效的名称 - 值对的参数,请参阅文档
  此功能。

'Pt' is not a recognized parameter. For a list of valid name-value pair arguments, see the documentation for this function.

函数code:

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

非常感谢您的帮助!

Thanks a lot for your help!

推荐答案

据错误,因为 PT 没有被指定为有效参数名称时,您最初分析的参数。你需要稍微调整了code,这里是我会怎么做:

It errors because Pt was not specified as a valid parameter name when you initially parsed the arguments. You need to slightly restructure the code, here is how I would do it:

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

这篇关于输入解析器相互依存的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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