Main Content

Evaluation of Expressions in Class Definitions

Why Use Expressions

An expression used in a class definition can be any valid MATLAB® statement that evaluates to a single array. Use expressions to define property default values and in attribute specifications. Expressions are useful to derive values in terms of other values. For example, suppose that you want to define a constant property with the full precision value of 2π. You can assign the property the value returned by the expression 2*pi. MATLAB evaluates the function when first loading the class.

For information on assigning property default values and attribute values, see Initialize Property Values and Property Attributes.

Where to Use Expressions in Class Definitions

Here are some examples of expressions used in a class definition:

classdef MyClass
   % Some attributes are set to logical values
   properties (Constant = true)
      CnstProp = 2*pi
   end
   properties
      % Static method of this class
      Prop1 = MyClass.setupAccount
      % Constant property from this class
      Prop2 = MyClass.CnstProp
      % Function that returns a value
      Prop3 = datestr(now)
      % A class constructor
      Prop4 = AccountManager
   end
   methods (Static)
      function accNum = setupAccount
         accNum = randi(9,[1,12]);
      end
   end
end

MATLAB does not call property set methods when assigning the result of default value expressions to properties. (See Property Get and Set Methods for information about these special methods.)

Enumerations that derived from MATLAB types can use expressions to assign a value:

classdef FlowRate < int32
   enumeration
      Low    (10)
      Medium (FlowRate.Low*5)
      High   (FlowRate.Low*10)
   end
end

MATLAB evaluates these expressions only once when enumeration members are first accessed.

Expressions in Attribute Specifications

For attributes values that are logical true or false, class definitions can specify attribute values using expressions. For example, this assignment makes MyClass sealed (cannot be subclassed) for versions of MATLAB before R2014b (verLessThan)

classdef  (Sealed = verLessThan('matlab','8.4')) MyClass

The expression on the right side of the equal sign (=) must evaluate to true or false. You cannot use any definitions from the class file in this expression, including any constant properties, static methods, and local functions.

While you can use conditional expression to set attribute values, doing so can cause the class definition to change based on external conditions. Ensure that this behavior is consistent with your class design.

Note

The AllowedSubclasses and the InferiorClasses attributes require an explicit specification of a cell array of matlab.metadata.Class objects as their values. You cannot use expressions to return these values.

Expressions That Specify Default Property Values

Property definitions allow you to specify default values for properties using any expression that has no reference to variables. For example, VectorAngle defines a constant property (Rad2Deg) and uses it in an expression that defines the default value of another property (Angle). The default value expression also uses a static method (getAngle) defined by the class:

classdef VectorAngle
   properties (Constant)
      Rad2Deg = 180/pi
   end
   properties
      Angle = VectorAngle.Rad2Deg*VectorAngle.getAngle([1 0],[0 1])
   end
   methods
      function obj = VectorAngle(vx,vy)
         obj.Angle = VectorAngle.getAngle(vx,vy);
      end
   end
   methods (Static)
      function r = getAngle(vx,vy)
         % Calculate angle between 2D vectors
         cr = vx(1)*vy(1) + vx(2)*vy(2)/sqrt(vx(1)^2 + vx(2)^2) * ...
            sqrt(vy(1)^2 + vy(2)^2);
         r = acos(cr);
      end
   end
end

You cannot use the input variables to the constructor to define the default value of the Angle property. For example, this definition for the Angle property is not valid:

properties
      Angle = VectorAngle.Rad2Deg*VectorAngle.getAngle(vx,vy)
end

Attempting to create an instance causes an error:

a = VectorAngle([1,0],[0,1])
Error using VectorAngle
Unable to update the class 'VectorAngle' because the new definition contains an
error:
 Undefined function or variable 'vx'.

Expressions in Class Methods

Expression in class methods execute like expressions in any function. MATLAB evaluates an expression within the function workspace when the method executes. Therefore, expressions used in class methods are not considered part of the class definition and are not discussed in this section.

How MATLAB Evaluates Expressions

MATLAB evaluates the expressions used in the class definition without any workspace. Therefore, these expressions cannot reference variables of any kind.

MATLAB evaluates expressions in the context of the class file, so these expressions can access any functions, static methods, and constant properties of other classes that are on your path at the time MATLAB initializes the class. Expressions defining property default values can access constant properties defined in their own class.

When MATLAB Evaluates Expressions

MATLAB evaluates the expressions in class definitions only when initializing the class. Initialization occurs before the first use of the class.

After initialization, the values returned by these expressions are part of the class definition and are constant for all instances of the class. Each instance of the class uses the results of the initial evaluation of the expressions without re-evaluation.

If you clear a class, then MATLAB reinitializes the class by reevaluating the expressions that are part of the class definition. (see Automatic Updates for Modified Classes)

Expression Evaluation in Handle and Value Classes

The following example shows how value and handle object behave when assigned to properties as default values. Suppose that you have the following classes.

Expressions in Value Classes

The ClassExp class has a property that contains a ContClass object:

classdef ContClass
   properties
      % Assign current date and time
      TimeProp = datestr(now) 
   end
end
classdef ClassExp
   properties
      ObjProp = ContClass
   end
end

When you first use the ClassExp class, MATLAB creates an instance of the ContClass class. MATLAB initializes both classes at this time. All instances of ClassExp include a copy of this same instance of ContClass.

a = ClassExp;
a.ObjProp.TimeProp
ans =

08-Oct-2003 17:16:08

The TimeProp property of the ContClass object contains the date and time when MATLAB initialized the class. Creating additional instances of the ClassExp class shows that the date string has not changed:

b = ClassExp;
b.ObjProp.TimeProp
ans =

08-Oct-2003 17:16:08

Because this example uses a value class for the contained object, each instance of the ClassExp has its own copy of the object. For example, suppose that you change the value of the TimeProp property on the object contained by ClassExp objectb:

b.ObjProp.TimeProp = datestr(now)
ans =

08-Oct-2003 17:22:49

The copy of the object contained by object a is unchanged:

a.ObjProp.TimeProp
ans =

08-Oct-2003 17:16:08

Expressions in Handle Classes

Now consider the behavior if the contained object is a handle object:

classdef ContClass < handle
   properties
      TimeProp = datestr(now)
   end
end

Creating two instances of the ClassExp class shows that MATLAB created an object when it initialized the ContClass. MATLAB used a copy of the object’s handle for each instance of the ClassExp class. Therefore, there is one ContClass object and the ObjProp property of each ClassExp object contains a copy of its handle.

Create an instance of the ClassExp class and note the time of creation:

a = ClassExp;
a.ObjProp.TimeProp
ans =

08-Oct-2003 17:46:01

Create a second instance of the ClassExp class. The ObjProp contains the handle of the same object:

b = ClassExp;
b.ObjProp.TimeProp
ans =

08-Oct-2003 17:46:01

Reassign the value of the contained object TimeProp property:

b.ObjProp.TimeProp = datestr(now);
b.ObjProp.TimeProp
ans =

08-Oct-2003 17:47:34

The ObjProp property of object b contains a handle to the same object as the ObjProp property of object a. The value of the TimeProp property has changed on this object as well:

a.ObjProp.TimeProp
ans =

08-Oct-2003 17:47:34

Related Topics