parse
解析函数输入
说明
示例
创建一个输入解析器模式,以检查必需输入是否为非负的数值标量。语法 @(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(可选参量)。由于可选参量是位置参量,因此如果height是findArea函数的参量,则它必须是第二个参量。输入解析器检查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 中推出
另请参阅
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
选择网站
选择网站以获取翻译的可用内容,以及查看当地活动和优惠。根据您的位置,我们建议您选择:。
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 MathWorks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- América Latina (Español)
- Canada (English)
- United States (English)
欧洲
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)