Main Content

mustBeNumeric

Validate that value is numeric

Description

example

mustBeNumeric(value) throws an error if value contains nonnumeric. This function does not return a value.

mustBeNumeric calls the following function to determine if the input is numeric:

This function ignores input arguments that are empty values. Therefore, no error is thrown when the property or function argument value is empty.

Examples

collapse all

Validate that the result of an operation is numeric.

mustBeNumeric(5 < 10)
Error using mustBeNumeric (line 10)
Values must be numeric.

The relational operator for less than returns a logical value.

This class restricts the value of Prop1 to numeric values.

classdef MyClass
   properties
      Prop1 {mustBeNumeric}
   end
end

Create an object and assign a value to its property.

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

When you assign a value to the property, MATLAB® calls mustBeNumeric with the value being assigned to the property. mustBeNumeric issues an error because the value assigned to Prop1 is a logical.

This function restricts the input argument to a numeric vector.

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

Calling this function with a character vector results in an error being thrown by mustBeNumeric.

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

Input Arguments

collapse all

Value to validate, specified as a scalar or array of any of the following:

  • Any MATLAB numeric class

  • MATLAB classes that derive from a MATLAB numeric type or that overload isnumeric

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
Complex Number Support: Yes

Tips

  • mustBeNumeric is designed to be used for property and function argument validation.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Introduced in R2017a