Main Content

mustBePositive

Validate that value is positive

Description

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

mustBePositive calls these functions to determine if the input is not positive:

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

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 the input contains only positive values.

The rand function creates a uniformly distributed random number.

A = rand(1,5) -0.5;

Validate that array elements are positive.

mustBePositive(A)
Value must be positive.

The result of subtracting 0.5 from the array return by rand can contain negative numbers. When a value is negative, 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 the following:

Tips

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