MATLAB 帮助中心
验证值为正
mustBePositive(value)
如果 value 不是正值,mustBePositive(value) 将抛出错误。大于零的值即为正值。此函数不返回值。
value
mustBePositive 调用 gt 函数来确定输入是否为正值。 (自 R2026a 起)
mustBePositive
gt
支持的类:实现 gt 的所有数值类、logical 和 MATLAB® 类。
logical
此函数忽略输入参量中的空值。因此,当属性或函数参量值为空时,不会抛出错误。
示例
全部折叠
使用 mustBePositive 验证数组是否仅包含正值。
创建一个均匀分布的随机数数组。
A = rand(1,5) - 0.5;
验证数组元素是否为正值。
mustBePositive(A)
Value must be positive.
从 0.5 返回的数组减去 rand 所得的结果可能包含负数值或零。当值不是正数时,mustBePositive 发出错误。
0.5
rand
该类将 Prop1 的值限制为正值。
Prop1
classdef MyClass properties Prop1 {mustBePositive} end end
创建一个对象,并向其属性赋值。
obj = MyClass; obj.Prop1 = 0;
Error setting property 'Prop1' of class 'MyClass'. Value must be positive.
当您向属性赋值时,MATLAB 会使用赋给属性的值调用 mustBePositive。mustBePositive 将引发错误,因为值 0 不为正。
0
此函数声明两个输入参量。输入 A 必须为数值向量。输入 ix 必须为正整数。
A
ix
function r = mbPositive(A,ix) arguments A (1,:) {mustBeNumeric} ix {mustBePositive, mustBeInteger} end r = A(ix); end
使用不满足 mustBePositive 要求的 ix 值调用该函数会引发错误。
A = 1:10; ix = 0; r = mbPositive(A,ix);
Error using mbPositive (line 4) r = mbPositive(A,ix); ^^ Invalid argument at position 2. Value must be positive.
要验证的值,指定为标量或由以下类型之一的值组成的数组:
logical 或数值类
实现 gt 的 MATLAB 类
数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string | categorical | datetime | duration | table | timetable 复数支持: 是
single
double
int8
int16
int32
int64
uint8
uint16
uint32
uint64
char
string
categorical
datetime
duration
table
timetable
mustBePositive 用于属性和函数参量验证。
全部展开
mustBePositive 函数完全支持 GPU 数组。要在 GPU 上运行该函数,请将输入数据指定为 gpuArray (Parallel Computing Toolbox)。有关详细信息,请参阅在 GPU 上运行 MATLAB 函数 (Parallel Computing Toolbox)。
gpuArray
mustBePositive 函数完全支持分布式数组。有关详细信息,请参阅使用分布式数组运行 MATLAB 函数 (Parallel Computing Toolbox)。
mustBePositive 函数不再调用 isreal、isnumeric 和 islogical 函数来验证输入。因此,mustBePositive 接受基础比较运算符 gt(或 >)支持的任何数据类型,例如字符向量、字符串以及日期和时间类型。
isreal
isnumeric
islogical
>
例如,MyClass 中的 Interval 属性定义使用 mustBePositive 验证函数来限制属性值。
MyClass
Interval
classdef MyClass properties Interval {mustBePositive} end end
A = datetime("yesterday"); B = datetime("today"); s = MyClass; s.Interval = B - A;
在以前的版本中,将 Interval 属性指定为 duration 值会返回以下错误:
Error setting property 'Interval' of class 'MyClass'. Value must be numeric or logical.
要保留以前版本的行为,请在您的验证检查中显式使用 mustBeReal 和 mustBeNumericOrLogical。例如,以下代码保留 mustBePositive 属性定义中 Interval 的先前行为。
mustBeReal
mustBeNumericOrLogical
classdef MyClass properties Interval {mustBeReal,mustBeNumericOrLogical, ... mustBePositive} end end
arguments | mustBeNumericOrLogical | mustBeReal | mustBeNonnegative | mustBeNonzero
arguments
mustBeNonnegative
mustBeNonzero
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 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
欧洲
亚太
联系您当地的办事处