Main Content

mustBeNonnegative

Validate that value is nonnegative

Description

mustBeNonnegative(value) throws an error if value is negative. This function does not return a value.

mustBeNonnegative calls these functions to determine if the input is not negative:

Class support: All numeric classes, logical, and MATLAB® classes that overload the functions called by mustBeNonnegative.

example

Examples

collapse all

Use mustBeNonnegative to validate that the input contains only nonnegative values.

The randn function creates normally distributed random numbers.

A = randn(1,5);

Validate that the random numbers are nonnegative.

mustBeNonnegative(A)
Value must be nonnegative.

This class restricts the value of Prop1 to nonnegative values.

classdef MyClass
   properties
      Prop1 {mustBeNonnegative}
   end
end

Create an object and assign a value to its property.

obj = MyClass;
obj.Prop1 = -10;
Error setting property 'Prop1' of class 'MyClass'. Value must be nonnegative.

When you assign a value to the property, MATLAB calls mustBeNonnegative with the value being assigned to the property. mustBeNonnegative issues an error because the value -10 is negative.

This function declares two input arguments. Input lower must be not be positive and input upper must be positive.

function r = mbNonnegative(lower,upper)
    arguments
        lower {mustBeNonpositive}
        upper {mustBeNonnegative}
    end
    x = lower*pi:upper*pi;
    r = sin(x);
end

Calling the function with a value for upper that does not meet the requirements of mustBeNonnegative results an error.

r = mbNonnegative(-12,-4);
Error using mbNonnegative (line 4)
 r = mbNonnegative(-12,-4);
                       ^^
Invalid argument at position 2. Value must be nonnegative.

Input Arguments

collapse all

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

Example: value = 1 does not generate an error.

Tips

  • mustBeNonnegative 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™.

Version History

Introduced in R2017a