Main Content

mustBeNumeric

验证值为数值

说明

示例

如果 value 包含非数值,则 mustBeNumeric(value) 会引发错误。此函数不返回值。

mustBeNumeric 调用以下函数来确定输入是否为数值:

此函数忽略输入参量中的空值。因此,当属性或函数参量值为空时,不会引发错误。

示例

全部折叠

验证运算结果为数值。

mustBeNumeric(5 < 10)
Values must be numeric.

小于关系运算符返回的是一个逻辑值。

此类将 Prop1 的值限制为数值。

classdef MyClass
   properties
      Prop1 {mustBeNumeric}
   end
end

创建一个对象,并向其属性赋值。

obj = MyClass;
obj.Prop1 = isprime(29);
Error setting 'Prop1' property of 'MyClass' class:
Values must be numeric.

当您向属性赋值时,MATLAB® 会使用赋给属性的值调用 mustBeNumericmustBeNumeric 将引发错误,因为赋给 Prop1 的值为逻辑值。

此函数将输入参量限制为数值向量。

function r = mbNumeric(x)
    arguments
        x (1,:) {mustBeNumeric}
    end
    p = [3 2 1];
    r = polyval(p,x);
end

使用字符向量调用该函数会导致 mustBeNumeric 引发错误。

x = '4 3 2';
r = mbNumeric(x);
Error using mbNumeric
 r = mbNumeric(x);
               ↑
Invalid input argument at position 1. Value must be numeric.

输入参数

全部折叠

要验证的值,指定为标量或由以下任一类型的值组成的数组:

  • 任意 MATLAB 数值类

  • 从 MATLAB 数值类型派生的或重载 isnumeric 的 MATLAB 类

数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
复数支持:

提示

  • mustBeNumeric 用于属性和函数参量验证。

扩展功能

C/C++ 代码生成
使用 MATLAB® Coder™ 生成 C 代码和 C++ 代码。

版本历史记录

在 R2017a 中推出