주요 콘텐츠

mustBePositive

Validate that value is positive

Description

mustBePositive(value) throws an error if value is not positive. Values are positive when they are greater than zero. This function does not return a value.

mustBePositive calls the gt function to determine if the input is positive. (since R2026a)

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

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 mustBePositive to validate that an array contains only positive values.

Create a uniformly distributed array of random numbers.

A = rand(1,5) - 0.5;

Validate that the array elements are positive.

mustBePositive(A)
Value must be positive.

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

This class restricts the value of Prop1 to positive values.

classdef MyClass
   properties
      Prop1 {mustBePositive}
   end
end

Create an object and assign a value to its property.

obj = MyClass;
obj.Prop1 = 0;
Error setting property 'Prop1' of class 'MyClass'. Value must be positive.

When you assign a value to the property, MATLAB calls mustBePositive with the value being assigned to the property. mustBePositive issues an error because the value 0 is not positive.

This function declares two input arguments. Input A must be a numeric vector. Input ix must be a positive integer.

function r = mbPositive(A,ix)
    arguments
        A (1,:) {mustBeNumeric}
        ix {mustBePositive, mustBeInteger}
    end
    r = A(ix);
end

Calling the function with a value for ix that does not meet the requirement of mustBePositive results in an error.

A = 1:10;
ix = 0;
r = mbPositive(A,ix);
Error using mbPositive (line 4)
 r = mbPositive(A,ix);
                  ^^
Invalid argument at position 2. Value must be positive.

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 gt

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

  • mustBePositive 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