Main Content

parse

解析函数输入

说明

示例

parse(p,argList) 解析并验证 arglist 中的输入。

示例

全部折叠

创建一个输入解析器模式,以检查必需输入是否为非负的数值标量。语法 @(x) 创建具有一个输入的匿名函数的句柄。

p = inputParser;
argName = 'num';
validationFcn = @(x) (x > 0) && isnumeric(x) && isscalar(x);
addRequired(p,argName,validationFcn)

解析无效输入,例如 -1

parse(p,-1)
The value of 'num' is invalid. It must satisfy the function: @(x)(x>0)&&isnumeric(x)&&isscalar(x).

解析和验证必需和可选的函数输入。

在文件 findArea.m 中创建一个函数。findArea 函数要求必须指定 width 输入参量,并接受可变数目的附加输入。输入解析器模式指定以下参量条件:

  • width(必需参量)。由于必需参量是位置参量,因此 width 必须是 findArea 函数的第一个参量。输入解析器检查 width 是否为正数值标量。

  • height(可选参量)。由于可选参量是位置参量,因此如果 heightfindArea 函数的参量,则它必须是第二个参量。输入解析器检查 height 是否为正数值标量。

  • 'units' 及其关联值(名称-值对组)。名称-值对组是可选的。当您调用 findArea 函数时,可在位置参量后面以任何顺序指定名称-值对组。输入解析器检查 'units' 的值是否为字符串。

  • 'shape' 及其关联值(另一个名称-值对组)。输入解析器检查 'shape' 的值是否包含在 expectedShapes 数组中。

function a = findArea(width,varargin)
   defaultHeight = 1;
   defaultUnits = 'inches';
   defaultShape = 'rectangle';
   expectedShapes = {'square','rectangle','parallelogram'};

   p = inputParser;
   validScalarPosNum = @(x) isnumeric(x) && isscalar(x) && (x > 0);
   addRequired(p,'width',validScalarPosNum);
   addOptional(p,'height',defaultHeight,validScalarPosNum);
   addParameter(p,'units',defaultUnits,@isstring);
   addParameter(p,'shape',defaultShape,...
                 @(x) any(validatestring(x,expectedShapes)));
   parse(p,width,varargin{:});
   
   a = p.Results.width*p.Results.height; 
end

多次调用 findArea 函数。输入解析器不会对以下任何函数调用引发错误。

a = findArea(7);
a = findArea(7,3);
a = findArea(13,'shape','square');
a = findArea(13,'units',"miles",'shape','square');

使用与输入解析器模式不匹配的参量调用该函数。为 width 输入指定一个非数字值:

a = findArea('text')
Error using findArea (line 14)
The value of 'width' is invalid. It must satisfy the function: @(x)isnumeric(x)&&isscalar(x)&&(x>0).

'shape' 指定一个不支持的值。

a = findArea(4,12,'shape','circle')
Error using findArea (line 14)
The value of 'shape' is invalid. Expected input to match one of these values:

'square', 'rectangle', 'parallelogram'

The input, 'circle', did not match any of the valid values.

输入参数

全部折叠

输入解析器模式,指定为 inputParser 对象。

要解析和验证的输入,以逗号分隔的列表形式指定。argList 的元素可以是任何数据类型。输入解析器使用您在输入解析器模式中添加参量时指定的验证函数来确定参量的有效性。

示例: 'textA',13,mtxB

示例: varargin{:}

扩展功能

基于线程的环境
使用 MATLAB® backgroundPool 在后台运行代码或使用 Parallel Computing Toolbox™ ThreadPool 加快代码运行速度。

版本历史记录

在 R2007a 中推出