MATLAB 帮助中心
验证值为整数
mustBeInteger(value)
如果 value 不包含整数值,mustBeInteger(value) 会抛出错误。此函数测试数字是否带有小数部分。此处不考虑值的数据类型。mustBeInteger 不返回值。
value
mustBeInteger
mustBeInteger 调用以下函数来确定 value 是否为整数: (自 R2026a 起)
isfinite
floor
eq
支持的类:实现 mustBeInteger 调用的函数的所有数值类、logical 和 MATLAB® 类。
logical
此函数忽略输入参量中的空值。因此,当属性或函数参量值为空时,不会抛出错误。
示例
全部折叠
验证计算结果是整数值。
A = randi(9)/randi(9); mustBeInteger(A)
Value must be integer.
如果两个随机整数相除的结果带有小数部分,mustBeInteger 会引发错误。
此类将 Prop1 的值限制为整数值。
Prop1
classdef MyClass properties Prop1 {mustBeInteger} end end
创建一个对象,并向其属性赋值。将两个随机整数相除,得到的可以是整数,也可以是带有小数部分的数。
obj = MyClass; obj.Prop1 = randi(9)/randi(9);
Error setting property 'Prop1' of class 'MyClass'. Value must be integer.
当您向属性赋值时,MATLAB 会使用赋给属性的值调用 mustBeInteger。当这些特定随机整数的除法运算的结果值不是整数时,mustBeInteger 将引发错误。
此函数声明两个输入参量。输入 A 必须为数值行向量。输入 idx 必须为整数标量。
A
idx
function r = mbInteger(A,idx) arguments A (1,:) {mustBeNumeric} idx (1,1) {mustBeInteger} end r = A(idx).^2; end
使用 idx 的非整数值调用该函数会导致 mustBeInteger 抛出错误。将两个随机整数相除,得到的可以是整数,也可以是带有小数部分的数。
idx = randi(9)/randi(9); A = rand(1,10); r = mbInteger(A,idx);
Error using mbInteger (line 4) r = mbInteger(A,idx); ^^^ Invalid argument at position 2. Value must be integer.
要验证的值,指定为标量或由以下类型之一的值组成的数组:
logical、char 或数值类
char
实现 eq、isfinite 和 floor 的 MATLAB 类
其他数据类型会导致错误。
数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | char | logical
single
double
int8
int16
int32
int64
uint8
uint16
uint32
uint64
mustBeInteger 用于属性和函数参量验证。
全部展开
mustBeInteger 函数完全支持 GPU 数组。要在 GPU 上运行该函数,请将输入数据指定为 gpuArray (Parallel Computing Toolbox)。有关详细信息,请参阅在 GPU 上运行 MATLAB 函数 (Parallel Computing Toolbox)。
gpuArray
mustBeInteger 函数完全支持分布式数组。有关详细信息,请参阅使用分布式数组运行 MATLAB 函数 (Parallel Computing Toolbox)。
mustBeInteger 函数不再调用 isreal、isnumeric 和 islogical 函数来验证输入。因此,mustBeInteger 接受它调用的基础函数(isfinite、floor 和 eq)支持的任何数据类型,例如字符向量。
isreal
isnumeric
islogical
例如,MyClass 中的 Interval 属性定义使用 mustBeInteger 验证函数来限制属性值。
MyClass
Interval
classdef MyClass properties Interval {mustBeInteger} end end
s = MyClass; s.Interval = 'abc';
在以前的版本中,将 Interval 属性指定为字符向量会返回以下错误:
Error setting property 'Interval' of class 'MyClass'. Value must be numeric or logical.
要保留以前版本的行为,请在您的验证检查中显式使用 mustBeReal 和 mustBeNumericOrLogical。例如,以下代码保留 mustBeInteger 属性定义中 Interval 的先前行为。
mustBeReal
mustBeNumericOrLogical
classdef MyClass properties Interval {mustBeReal,mustBeNumericOrLogical, ... mustBeInteger} end end
arguments | mustBeNumericOrLogical | mustBeReal | mustBeNumeric | mustBePositive
arguments
mustBeNumeric
mustBePositive
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 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
欧洲
亚太
联系您当地的办事处