Main Content

mustBeInRange

Validate that value is in the specified range

Since R2020b

    Description

    mustBeInRange(value,lower,upper) throws an error if any element of value is not within the range defined by lower and upper. A value is within the range if it is greater than or equal to lower, and less than or equal to upper. This function does not return a value.

    mustBeInRange calls these functions to determine if value is in the specified range:

    Class support: All numeric classes and logical.

    example

    mustBeInRange(value,lower,upper,boundflag1,boundflag2) Uses optional flags boundflag1 and boundflag2 to indicate if the upper or lower bound is included in the range.

    example

    Examples

    collapse all

    Use the mustBeInRange function to restrict the range of allowed values.

    mustBeInRange(255,0,1)
    Value must be greater than or equal to 0, and less than or equal to 1.

    Values outside the range result in an error.

    Use the mustBeInRange function to restrict the range of values that can be passed to a function.

    The inRange function restricts its input to values in the range of 0 to less than 100.

    function r = inRange(a)
        arguments
            a {mustBeInRange(a,0,100,"exclude-upper")}
        end
        r = a;
    end

    Passing the array [2 5 100] throws an error.

    r = inRange([2 5 100])
    Error using inRange (line 3)
     r = inRange([2 5 100])
                 ^^^^^^^^^
    Invalid argument at position 1. Value must be greater than or equal to 0, and less than 100.

    Input Arguments

    collapse all

    Value to validate, specified as a scalar or array of numeric, logical, or user-defined types that support the relational operators, >, >=, <, and <=.

    Lower bound of range, specified as a value of the same type as value.

    Upper bound of range, specified as a value of the same type as value.

    Include or exclude the upper or lower bound in the range, specified as one or two of the following:

    • inclusive – Include the lower and upper values in the range of allowed values.

    • exclusive – Exclude the lower and upper values from the range of allowed values.

    • exclude-lower – Exclude the lower value from the range of allowed values.

    • exclude-upper – Exclude the upper value from the range of allowed values.

    Use no more than two of these flags to indicate if the lower bound and upper bound should be excluded from or included in a range. The only valid combination of these flags is exclude-lower and exclude-upper. This combination is equivalent to using only exclusive.

    Data Types: char | string

    Tips

    • mustBeInRange 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 R2020b