Main Content

mustBeNegative

Validate that value is negative

Description

mustBeNegative(value) throws an error if value is not negative. A value is negative if it is less than zero. This function does not return a value.

mustBeNegative calls the lt function to determine if the input is negative. (since R2026a)

Class support: All numeric classes, logical, and MATLAB® classes that implement lt.

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

example

Examples

collapse all

Use mustBeNegative to validate that an array contains only negative values.

Create a uniformly distributed array of random numbers.

A = rand(1,5) - 0.75;

Validate that the array elements are negative.

mustBeNegative(A)
Value must be negative.

The result of subtracting 0.75 from the array returned by rand can contain positive numbers or zeros. When a value is not negative, mustBeNegative issues an error.

This class restricts the value of Prop1 to negative values.

classdef MyClass
   properties
      Prop1 {mustBeNegative}
   end
end

Create an object and assign a value to Prop1.

obj = MyClass;
obj.Prop1 = rand(1,5) - 0.75;
Error setting property 'Prop1' of class 'MyClass'. Value must be negative.

When you assign a value to the property, MATLAB calls mustBeNegative with the value being assigned to the property. mustBeNegative issues an error if the any of the elements in the array are not negative.

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

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

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

mbNegative(0,4)
Error using mbNegative (line 3)
 mbNegative(0,4)
            ^
Invalid argument at position 1. Value must be negative.

Input Arguments

collapse all

Value to validate, specified as a scalar or an array of one of these types:

  • logical or numeric class

  • MATLAB classes that implement lt

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string | categorical | datetime | duration | table | timetable
Complex Number Support: Yes

Tips

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

Extended Capabilities

expand all

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

GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Version History

Introduced in R2017a

expand all