Validate that value is positive or issue error



mustBePositive(value) issues 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 accepts user-defined objects if the class of the object implements these methods:

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


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.

Error using mustBePositive (line 14)
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
      Prop1 {mustBePositive}

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)
        A (1,:) {mustBeNumeric}
        ix {mustBePositive, mustBeInteger}
    r = A(ix);

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
Invalid input 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:

Extended Capabilities

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

Introduced in R2017a