mustBeMember
验证值是指定集的成员
说明
示例
验证第一个输入是集合的成员
使用 mustBeMember
验证第一个输入是第二个输入指定的值集合的成员。
验证字符向量 'red'
是字符向量 'yellow'
、'green'
和 'blue'
集合的成员。
A = 'red'; B = {'yellow','green','blue'}; mustBeMember(A,B)
Value must be a member of this set 'yellow' 'green' 'blue'
验证失败,因为 'red'
不是集合的成员。MATLAB 返回列出允许值的错误消息。
限制属性值
此类将属性的值限制为一组特定的值。
Prop1
的值必须为 'yellow'
、'green'
或 'blue'
。
classdef MyClass properties Prop1 {mustBeMember(Prop1,{'yellow','green','blue'})} = 'yellow' end end
默认属性值必须符合验证函数所施加的限制。因此,必须为其显式指定一个属于集合成员的默认值。
创建一个对象,并向其属性赋值。
obj = MyClass
obj.Prop1 = 'red';
Error setting 'Prop1' property of 'MyClass' class. Value must be a member of this set 'yellow' 'green' 'blue'
验证失败,因为 'red'
不是集合的成员。MATLAB 返回列出允许值的错误消息。
限制函数参数值
此函数声明两个输入参数。输入 n
必须为标量数值,输入 typename
必须为字符向量 single
或 double
。
function r = mbMember(n,typename) arguments n (1,1) {mustBeNumeric} typename {mustBeMember(typename,{'single','double'})} = 'single' end r = rand(n,typename); end
此函数调用使用的 typename
值不满足 mustBeMember
定义的要求,并会引发错误。
r = mbMember(5,'int32');
Error using mbMember r = mbMember(5,'int32'); ↑ Invalid input argument at position 2. Value must be a member of this set: 'single' 'double'
输入参数
value
— 要验证的值
标量 | 数组
要验证的值,指定为标量或由以下任一类型的值组成的数组:
将 mustBeMember
用作属性验证函数时,此参数必须是属性名称,且不带引号。
示例: PropName {mustBeMember(PropName,{'High','Medium','Low'})} = 'Low'
数据类型: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| logical
| char
| string
| cell
复数支持: 是
S
— value
必须属于的值集合
标量 | 数组
value
必须属于的值集合,指定为以下任一值:
示例: 值为 char
向量元胞数组的属性:PropName {mustBeMember(PropName,{'yellow','green','blue'})} = 'blue'
示例: 值为字符串数组的属性:PropName {mustBeMember(PropName,["yellow","green","blue"])} = "blue"
数据类型: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| logical
| char
| string
| cell
复数支持: 是
提示
mustBeMember
用于属性和函数参数验证。
扩展功能
C/C++ 代码生成
使用 MATLAB® Coder™ 生成 C 代码和 C++ 代码。
版本历史记录
在 R2017a 中推出
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)