Main Content

Set and Get Methods for Dynamic Properties

You can define property set access or get access methods for dynamic properties without creating additional class methods. For general information on the use of access methods, see Property Get and Set Methods.

Create Access Methods for Dynamic Properties

Use these steps to create a property access method:

  • Define a function that implements the operations you want to perform before the property set or get occurs. These methods must have the following signatures: mySet(obj,val) or val = myGet(obj)

  • Obtain the dynamic property's corresponding matlab.metadata.DynamicProperty object.

  • Assign a function handle referencing your set or get property function to the matlab.metadata.DynamicProperty object's GetMethod or SetMethod property. This function does not need to be a method of the class. You cannot use a naming scheme like set.PropertyName. Instead, use any other valid function name.

Suppose that you want to create a property set function for the myCoord dynamic property of the button class created in Define Dynamic Properties.

Write the function as follows.

function set_myCoord(obj,val)
   if  ~(length(val) == 2) 
      error('myCoords require two values')
   end
   obj.myCoord = val; 
end 

Because button is a handle class, the property set function does not need to return the object as an output argument.

To get the matlab.metadata.DynamicProperty object, use the handle class findprop method:

mb1 = b1.findprop('myCoord');
mb1.SetMethod = @set_myCoord;

MATLAB® calls the property set function whenever you set this property:

b1.myCoord = [1 2 3] % length must be two
Error using button.set_myCoord
myCoords require two values

You can set and get the property values only from within your property access methods. You cannot call another function from the set or get method, and then attempt to access the property value from that function.

Related Topics