Main Content

mustBeA

Validate that value comes from one of specified classes

Since R2020b

    Description

    mustBeA(value,classNames) compares value with a list of class names in classNames and throws an error if the class of value is not one of the named classes or a subclass of one of the named classes. This function does not return a value.

    Class support: All MATLAB® classes

    example

    Examples

    collapse all

    Validate that a value is a scalar or an array of type string or uint8.

    a = 'red';
    mustBeA(a,["string","uint8"])
    Value must be of the following types: 'string' or 'uint8'.

    Passing a character vector is not valid because mustBeA restricts text values to strings only.

    b = [1 0 0];
    mustBeA(b,["string","uint8"])
    Value must be of the following types: 'string' or 'uint8'.

    Passing an array of double integers is not valid because mustBeA restricts numeric values to uint8 only.

    Subclasses satisfy the "isa" relationship with superclasses. Therefore, a value that is a subclass of one of the specified classes is valid.

    Define a subclass of uint8.

    classdef ColorSpec < uint8
        methods
            function obj = ColorSpec(c)
                if nargin == 0
                    c = uint8(0);
                end
                obj = obj@uint8(c);
            end
        end
    end
    

    Create an object of the ColorSpec class.

    a = ColorSpec([1 0 0])
    a = 
    
      1×3 ColorSpec:
    
      uint8 data:
       1   0   0

    The ColorSpec object contains uint8 data.

    Test the validity of the ColorSpec object with mustBeA. The following statement does not produce an error.

    mustBeA(a,["string","uint8"])

    Input Arguments

    collapse all

    Value to validate, specified as a scalar or an array of any MATLAB or user-defined type.

    Names of one or more classes, specified as a string array, character vector, or cell array of character vectors.

    Example: ["double", "single"]

    Tips

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

    Extended Capabilities

    Thread-Based Environment
    Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

    Version History

    Introduced in R2020b