Main Content

Property Class and Size Validation

Property Class and Size

MATLAB® applies any class and size validation defined for a property before calling validation functions. Assignment to a property that defines size or class validation is analogous to assignment to a MATLAB object array. MATLAB can apply class and size conversions to the right side of the assignment to satisfy class and size validation.

For more information, see Order of Validation and Property Validation Functions.

Property Size Validation

Specify the property size as the row, column, and additional dimension following the property name.

classdef MyClass
   properties
      Prop(dim1,dim2,...) = defaultValue
   end
end

Assignment and Size Validation

This class defines the size of the Location property as 1-by-3. Any value assigned to this property must conform to that size or must be convertible to that size.

classdef ValidateProps
   properties
      Location(1,3)
   end
end

The implicit default value assigned by MATLAB, [0 0 0], conforms to the specified size:

a = ValidateProps
a = 

  ValidateProps with properties:

    Location: [0 0 0]

MATLAB applies scalar expansion when you assign a scalar the Location property.

a = ValidateProps;
a.Location = 1
a = 

  ValidateProps with properties:

    Location: [1 1 1]

MATLAB converts columns to rows to match the size specification:

col = [1;1;1]
col =

     1
     1
     1
a.Location = col
a = 

  ValidateProps with properties:

    Location: [1 1 1]

Colon in Size Specification

A colon in the size specification indicates that the corresponding dimension can have any length. For example, you can assign a row vector with any number of columns to the Data property in this class.

classdef ValidateProps
   properties
      Data(1,:)
   end
end
a = ValidateProps;
a.Data = [1:10]
a = 

  ValidateProps with properties:

    Data: [1 2 3 4 5 6 7 8 9 10]

Assignment to a property that defines size validation follows the same rules as the equivalent indexed array assignment. For information on indexing behavior of multidimensional arrays, see Compatible Array Sizes for Basic Operations.

Property Class Validation

Defining the class of a property can reduce the need to test the values assigned to the property in your code. In general, the value assigned to the property must be of the specified class or convertible to the specified class. An exception to this rule is for subclasses. If you specify a user-defined class as part of validation, subclasses of that class pass validation without error, but they are not converted.

You can specify only one class per property. Use validation functions like mustBeNumeric or mustBeInteger to restrict properties to a broader category of classes. For more information on validation functions, see Property Validation Functions.

You can use any MATLAB class or externally defined class that is supported by MATLAB, except Java® and COM classes.

Place the name of the class in the property definition block following the property name and optional size specification.

classdef MyClass
   properties
      Prop ClassName = defaultValue
   end
end

If you do not specify a default value, MATLAB assigns an empty object of the specified class to the property. If you define a size and a class, MATLAB attempts to create a default value for the property that satisfies both the size and class requirement.

MATLAB creates the default value by calling the class constructor with no arguments. The class must have a constructor that returns an object of the specified size when called with no input arguments or you must specify a default value for the property that satisfies the property size restriction. For more information, see Default Values Per Size and Class.

Using Class Validation

The PropsWithClass class defines two properties with class definitions:

  • Number — Values must be of class double or convertible to double.

  • Today — Values must be of class string or convertible to string. The default value is the current date, returned by the datetime function.

classdef PropsWithClass
   properties
      Number double
      Today string = datetime("today")
   end
end

Create an object of the PropsWithClass class.

p = PropsWithClass
p = 

  PropsWithClass with properties:

    Number: []
     Today: "09-Jun-2022"

MATLAB performs conversions from any compatible class to the property class. For example, assign a uint8 value to the Number property.

p.Number = uint8(5);
disp(class(p.Number))
ans =

double

Because the uint8 value can be converted to double, you can assign that uint8 value to the Number property.

Assigning an incompatible value to a property that uses class validation causes an error.

p.Number = datetime("today");
Error setting property 'Number' of class 'PropsWithClass':
Value must be double or be convertible to double.

User-Defined Class for Validation

You can define a class to control the values assigned to a property. Enumeration classes enable users to set property values to character vectors or string scalars with inexact name matching.

For example, suppose that there is a class that represents a three-speed mechanical pump. You can define an enumeration class to represent the three flow rates.

classdef FlowRate < int32
   enumeration
      Low    (10)
      Medium (50)
      High   (100)
   end
end

The Pump class has a method to return the current flow rate in gallons per minute. Define the Speed property as a FlowRate class.

classdef Pump
   properties
      Speed FlowRate
   end
   methods
      function getGPM(p)
         if isempty(p.Speed)
            gpm = 0;
         else
            gpm = int32(p.Speed);
         end
         fprintf('Flow rate is: %i GPM\n',gpm);
      end
   end
end

Users can set the Speed property using inexact text.

p = Pump;
p.Speed = 'm'
p = 

  Pump with properties:

    Speed: Medium

The numerical value is available from the property.

getGPM(p)
Flow rate is: 50 GPM

For information about enumeration classes, see Define Enumeration Classes.

Integer Class Validation

MATLAB supports several integer classes (see Integers). However, restricting a property to an integer class can result in integer overflow. The resulting value can saturate at the maximum or minimum value in the integer’s range.

When integer overflow occurs, the value that is assigned to a property can be a value that is different from the value from the right side of the assignment statement.

For example, suppose that you want to restrict a property value to a scalar uint8.

classdef IntProperty
   properties
      Value(1,1) uint8
   end
end

Assigning a numeric value to the Value property effectively casts the numeric value to uint8, but does not result in an error for out-of-range values.

a = IntProperty;
a.Value = -10;
disp(a.Value)
0

Assignment to the Value property is equivalent to indexed assignment of an array. If the assigned value is out of the range of values that uint8 can represent, MATLAB sets the value to the closest value that it can represent using uint8.

a = uint8.empty;
a(1) = -10
a =

  uint8

   0

To avoid the potential for integer overflow, use a combination of validation functions that restrict the value to the intended range instead of an integer class.

classdef IntProperty
   properties
      Value(1,1) {mustBeInteger, mustBeNonnegative,...
         mustBeLessThan(Value,256)}
   end
end

Because there is no conversion of the assigned value by the uint8 class, the validators catch out of range values and throw an appropriate error.

a = IntProperty;
a.Value = -10;
Error setting property 'Value' of class 'IntProperty':
Value must be nonnegative.

Default Values Per Size and Class

Any default property value that you assign in the class definition must conform to the specified validation.

Implicit Default Values

MATLAB defines a default value implicitly if you do not specify a default value in the class definition. This table shows how size and class determine the implicit default value of MATLAB classes.

SizeClassImplicit Default Assigned by MATLAB

(m,n)

Any numeric

m-by-n array of zeros of specified class.

(m,:) or (:,n)

Any class

m-by-0 or 0-by-n of specified class.

(m,n)

char

m-by-n char array of spaces.

(m,n)

cell

m-by-n cell array with each cell containing a 0-by-0 double.

(m,n)

struct

m-by-n struct

(m,n)

string

m-by-n string

(m,n)

enumeration class

First enumeration member defined in the class.

(1,1)

function_handle

Runtime error — define a default value in the class.

To determine the implicit default value for nonzero and explicit size specifications, MATLAB calls the default class constructor and builds an array of the specified size using the instance returned by the constructor call. If the class does not support a default constructor (that is, a constructor called with no arguments), then MATLAB throws an error when instantiating the class containing the validation.

If the specified size has any zero or unrestricted (:) dimensions, MATLAB creates a default value that is an empty array with the unrestricted dimension set to zero.

For heterogeneous arrays, MATLAB calls the matlab.mixin.Heterogeneous.getDefaultScalarElement method to get the default object.

Related Topics