addRequired
将必需的位置参数添加到输入解析器模式中
说明
示例
添加必需的输入
创建 inputParser
对象并将名为 myinput
的必需输入添加到输入方案。
p = inputParser;
argName = 'myinput';
addRequired(p,argName)
使用输入值 7 调用 parse
函数并显示结果。
parse(p,7) p.Results
ans = struct with fields:
myinput: 7
验证必需输入是否非负
创建一个输入解析器模式,以检查必需输入是否为非负的数值标量。语法 @(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).
使用 validateattributes
验证必需输入
创建一个 inputParser
对象,并使用 validateattributes
定义验证函数。验证函数测试必需输入是否为数值、正数且为偶数。
p = inputParser; argName = 'evenPosNum'; validationFcn = @(x) validateattributes(x,{'numeric'},... {'even','positive'}); addRequired(p,argName,validationFcn)
解析输入字符向量。解析失败,因为输入无效。
parse(p,'hello')
The value of 'evenPosNum' is invalid. Expected input to be one of these types: double, single, uint8, uint16, uint32, uint64, int8, int16, int32, int64 Instead its type was char.
解析奇数。解析失败,因为输入无效。
parse(p,13)
The value of 'evenPosNum' is invalid. Expected input to be even.
解析正偶数。解析通过。
parse(p,42)
输入参数
p
— 输入解析器模式
inputParser
对象
输入解析器模式,指定为 inputParser
对象。
argName
— 输入参数的名称
字符向量 | 字符串标量
输入参数的名称,指定为字符向量或字符串标量。
示例: 'firstName'
示例: 'address'
数据类型: char
| string
validationFcn
— 用于验证参数的函数
函数句柄
用于验证参数的函数,指定为函数句柄。
函数句柄必须与函数关联,该函数要么返回 true
或 false
,要么通过测试或引发错误。这两个类型的函数都必须接受单个输入参数。
示例: @(s)isstring(s)
示例: @(x)isnumeric(x)&&isscalar(x)
示例: @(n)validateattributes(n,{'numeric'},{'nonnegative'})
数据类型: function_handle
版本历史记录
在 R2007a 中推出
MATLAB 命令
您点击的链接对应于以下 MATLAB 命令:
请在 MATLAB 命令行窗口中直接输入以执行命令。Web 浏览器不支持 MATLAB 命令。
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- 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)