Main Content

Implement Set/Get Interface for Properties

The Standard Set/Get Interface

Some MATLAB® objects, such as graphics objects, implement an interface based on set and get functions. These functions enable access to multiple properties on arrays of objects in a single function call.

You can add set and get functionality to your class by deriving from one of these classes:

  • matlab.mixin.SetGet — use when you want support for case-insensitive, partial property name matching. Deriving from matlab.mixin.SetGet does not affect the exact property name required by the use of dot notation reference to properties.

  • matlab.mixin.SetGetExactNames — use when you want to support only case-sensitive full property name matching.

Note

The set and get methods referred to in this section are different from property set access and property get access methods. See Property Get and Set Methods for information on property access methods.

Subclass Syntax

Use the abstract class matlab.mixin.SetGet or matlab.mixin.SetGetExactNames as a superclass:

classdef MyClass < matlab.mixin.SetGet
   ...
end

Because matlab.mixin.SetGet and matlab.mixin.SetGetExactNames derive from the handle class, your subclass is also a handle class.

Get Method Syntax

The get method returns the value of an object property using the object handle and the property name. For example, assume H is the handle to an object:

v = get(H,'PropertyName');

If you specify an array of handles with a single property name, get returns the property value for each object as a cell array of values:

CV = get(H,'PropertyName');

The CV array is always a column regardless of the shape of H.

If you specify a cell array of char vector property names and an array of handles, get returns a cell array of property values. Each row in the cell corresponds to an object in the handle array. Each column in the cell corresponds to a property name.

props = {'PropertyName1','PropertyName2'};
CV = get(H,props);

get returns an m-by-n cell array, where m = length(H) and n = length(props).

If you specify a handle array, but no property names, get returns an array of type struct in which each structure in the array corresponds to an object in H. Each field in each structure corresponds to a property defined by the class of H. The value of each field is the value of the corresponding property.

SV = get(H);

If you do not assign an output variable, then H must be scalar.

For an example, see Using get with Arrays of Handles.

Set Method Syntax

The set method assigns the specified value to the specified property for the object with handle H. If H is an array of handles, MATLAB assigns the value to the property for each object in the array H.

set(H,'PropertyName',PropertyValue)

You can pass a cell array of property names and a cell array of property values to set:

props = {'PropertyName1','PropertyName2'};
vals = {Property1Value,Property2Value};
set(H,props,vals)

If length(H) is greater than one, then the property value cell array (vals) can have values for each property in each object. For example, suppose length(H) is 2 (two object handles). You want to assign two property values on each object:

props = {'PropertyName1','PropertyName2'};
vals = {Property11Value,Property12Value;Property21Value,Property22Value};
set(H,props,vals))

The preceding statement is equivalent to the follow two statements:

set(H(1),'PropertyName1',Property11Value,'PropertyName2',Property12Value)
set(H(2),'PropertyName1',Property21Value,'PropertyName2',Property22Value)

If you specify a scalar handle, but no property names, set returns a struct with one field for each property in the class of H. Each field contains an empty cell array.

SV = set(h);

Tip

You can use any combination of property name/property value cell arrays, structure arrays (with the field names as property names and field values as property values), and cell arrays in one call to set.

Class Derived from matlab.mixin.SetGet

This sample class defines a set/get interface and illustrates the behavior of the inherited methods:

classdef LineType < matlab.mixin.SetGet
   properties
      Style = '-'
      Marker = 'o'
   end
   properties (SetAccess = protected)
      Units = 'points'
   end
   methods
      function obj = LineType(s,m)
         if nargin > 0
            obj.Style = s;
            obj.Marker = m;
         end
      end
      function set.Style(obj,val)
         if ~(strcmpi(val,'-') ||...
               strcmpi(val,'--') ||...
               strcmpi(val,'..'))
            error('Invalid line style ')
         end
         obj.Style = val;
      end
      function set.Marker(obj,val)
         if ~isstrprop(val,'graphic')
            error('Marker must be a visible character')
         end
         obj.Marker = val;
      end
   end
end

Create an instance of the class and save its handle:

h = LineType('--','*');

Query the value of any object property using the inherited get method:

get(h,'Marker')
ans =

'*'

Set the value of any property using the inherited set method:

set(h,'Marker','Q')

Property Access Methods Called with set and get

MATLAB calls property access methods (set.Style or set.Marker in the LineType class) when you use the set and get methods.

set(h,'Style','-.-')
Error using LineType/set.Style (line 20)
Invalid line style

For more information on property access methods, see Property Get and Set Methods

List All Properties

Return a struct containing object properties and their current values using get:

h = LineType('--','*');
SV = get(h)
SV = 

  struct with fields:

     Style: '--'
    Marker: '*'
     Units: 'points'

Return a struct containing the properties that have public SetAccess using set:

S = set(h)
S = 

  struct with fields:

     Style: {}
    Marker: {}

The LineType class defines the Units property with SetAccess = protected. Therefore, S = set(h) does not create a field for Units in S.

set cannot return possible values for properties that have nonpublic set access.

Using get with Arrays of Handles

Suppose that you create an array of LineType objects:

H = [LineType('..','z'),LineType('--','q')]
H = 

  1x2 LineType with properties:

    Style
    Marker
    Units

When H is an array of handles, get returns a (length(H)-by-1) cell array of property values:

CV = get(H,'Style')
CV =

  2×1 cell array

    {'..'}
    {'--'}

When H is an array of handles and you do not specify a property name, get returns a struct array containing fields with names corresponding to property-names. Assign the output of get to a variable when H is not scalar.

SV = get(H)
SV = 

2x1 struct array with fields:
    Style
    Marker
    Units

Get the value of the Marker property from the second array element in the SV array of structures:

SV(2).Marker
ans =

'q'

Arrays of Handles, Names, and Values

You can pass an array of handles, a cell array of property names, and a cell array of property values to set. The property value cell array must have one row of property values for each object in H. Each row must have a value for each property in the property name array:

H = [LineType('..','z'),LineType('--','q')];
set(H,{'Style','Marker'},{'..','o';'--','x'})

The result of this call to set is:

H(1)
ans = 

  LineType with properties:

     Style: '..'
    Marker: 'o'
     Units: 'points
H(2)
ans = 

  LineType with properties:

     Style: '--'
    Marker: 'x'
     Units: 'points'

Customize the Property List

Customize the way property lists display by redefining the following methods in your subclass:

  • setdisp — When you call set with no output argument and a single scalar handle input, set calls setdisp to determine how to display the property list.

  • getdisp — When you call get with no output argument and a single scalar handle input, get calls getdisp to determine how to display the property list.

Set Priority for Matching Partial Property Names

Classes that derive from matlab.mixin.SetGet can use the PartialMatchPriority property attribute to specify a relative priority for partial name matching. MATLAB applies this attribute when resolving incomplete and case-insensitive text strings that match more than one property name.

The inherited set and get methods can resolve inexact property names when there are no ambiguities resulting from inexact name strings. When a partial property name is ambiguous because the name matches more than one property, the PartialMatchPriority attribute value can determine which property MATLAB matches.

The default priority is equivalent to PartialMatchPriority = 1. To reduce the relative priority of a property, set PartialMatchPriority to a positive integer value of 2 or greater. The priority of a property decreases as the value of PartialMatchPriority increases.

For example, in this class the Verbosity property has a higher priority for name matching than the Version property.

classdef MyClass < matlab.mixin.SetGet
    properties
        Verbosity
    end
    properties (PartialMatchPriority = 2)
        Version
    end
end

Calling the set method with the potentially ambiguous inexact name Ver sets the Verbosity property because of its higher relative priority. Without setting the PartialMatchPriority attribute, the ambiguous name would cause an error.

a = MyClass;
set(a,"Ver",10)
disp(a)
 MyClass with properties:

    Verbosity: 10
      Version: []

The same name selection applies to the get method.

v = get(a,"Ver")
v =

    10 

Case and Name Matching

A full name match with nonmatching case takes precedence over a partial match with a higher priority property. For example, this class defines the BaseLine property with a priority of 1 (the default) and a Base property with a priority of 2 (lower than 1).

classdef MyClass < matlab.mixin.SetGet
    properties
        BaseLine
    end
    properties (PartialMatchPriority = 2)
        Base
    end
end

Calling the set method with the string base sets the Base property. BaseLine has a higher priority, but the full name match with incorrect case takes precedence.

a = MyClass;
set(a,"base",-2)
disp(a)
 MyClass with properties:

    BaseLine: []
        Base: -2

Reduce Incompatibilities When Adding New Properties

You can use the PartialMatchPriority attribute to avoid introducing code incompatibilities when adding a new property. For example, this class enables the set and get methods to refer to the Distance property with the string Dis because the DiscreteSamples property has a lower priority.

classdef Planet < matlab.mixin.SetGet
% Version 1.0
    properties
        Distance
    end
    properties(PartialMatchPriority = 2)
        DiscreteSamples
    end
end

Version 2.0 of the class introduces a property named Discontinuities. To prevent the possibility of causing an ambiguous partial property name in existing code, use PartialMatchPriority to set the priority of Discontinuities lower than that of previously existing properties.

classdef Planet < matlab.mixin.SetGet
% Version 2.0
    properties
        Diameter;
        NumMoons = 0
        ApparentMagnitude;
        DistanceFromSun;
    end
    properties(PartialMatchPriority = 2)
        DiscreteSamples;
    end
    properties(PartialMatchPriority = 3)
        Discontinuities = false;
    end
end

For version 1.0 of the Planet class, this call to the set method was not ambiguous.

p = Planet;
set(p,"Disc",true)

However, with the introduction of the Discontinuities property, the string Disc becomes ambiguous. By giving the Discontinuities property a lower priority, the string Disc continues to match the DiscreteSamples property.

Note

When writing reusable code, using complete, case-sensitive property names avoids ambiguities, prevents incompatibilities with subsequent software releases, and produces more readable code.

See Also

| | |

Related Topics