mustBeNonnegative
验证值为非负值
说明
示例
使用 mustBeNonnegative 验证输入只包含非负值。
该类将 Prop1 的值限制为非负值。
classdef MyClass properties Prop1 {mustBeNonnegative} end end
创建一个对象,并向其属性赋值。
obj = MyClass; obj.Prop1 = -10;
Error setting property 'Prop1' of class 'MyClass'. Value must be nonnegative.
当您向属性赋值时,MATLAB 会使用赋给属性的值调用 mustBeNonnegative。mustBeNonnegative 将引发错误,因为值 -10 为负。
此函数声明两个输入参量。输入 lower 不能为正数,输入 upper 必须为正数。
function r = mbNonnegative(lower,upper) arguments lower {mustBeNonpositive} upper {mustBeNonnegative} end x = lower*pi:upper*pi; r = sin(x); end
使用不满足 mustBeNonnegative 要求的 upper 值调用该函数会引发错误。
r = mbNonnegative(-12,-4);
Error using mbNonnegative (line 4)
r = mbNonnegative(-12,-4);
^^
Invalid argument at position 2. Value must be nonnegative.输入参数
提示
mustBeNonnegative用于属性和函数参量验证。
扩展功能
C/C++ 代码生成
使用 MATLAB® Coder™ 生成 C 代码和 C++ 代码。
GPU 代码生成
使用 GPU Coder™ 为 NVIDIA® GPU 生成 CUDA® 代码。
mustBeNonnegative 函数完全支持 GPU 数组。要在 GPU 上运行该函数,请将输入数据指定为 gpuArray (Parallel Computing Toolbox)。有关详细信息,请参阅在 GPU 上运行 MATLAB 函数 (Parallel Computing Toolbox)。
mustBeNonnegative 函数完全支持分布式数组。有关详细信息,请参阅使用分布式数组运行 MATLAB 函数 (Parallel Computing Toolbox)。
版本历史记录
在 R2017a 中推出mustBeNonnegative 函数不再调用 isreal、isnumeric 和 islogical 函数来验证输入。因此,mustBeNonnegative 接受基础比较运算符 ge(或 >=)支持的任何数据类型,例如字符向量、字符串以及日期和时间类型。
例如,MyClass 中的 Interval 属性定义使用 mustBeNonnegative 验证函数来限制属性值。
classdef MyClass properties Interval {mustBeNonnegative} end end
duration 的值。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。例如,以下代码保留 mustBeNonnegative 属性定义中 Interval 的先前行为。
classdef MyClass properties Interval {mustBeReal,mustBeNumericOrLogical, ... mustBeNonnegative} end end
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)