Main Content

matlab.System Constructor

Construct System object with Name,Value pairs or value-only inputs

Description

function obj = ObjectName(varargin) constructs an ObjectName System object™ and sets properties from name-value pair inputs.

The System object constructor is a public method in the class file. The method name matches the class name. When you create a System object, the constructor is called to initialize properties to nondefault values. The constructor returns a new System object.

Constructor Body

Inside the constructor, call setProperties using one of the syntaxes in the table.

Input ArgumentsConstructor BodyExample
Name,Value pairssetProperties(obj, nargin, varargin{:})Constructor for Name-Value Pairs
Name,Value pairs and value-only argumentssetProperties(obj, nargin, varargin{:}, 'Prop1', ..., 'PropN')Constructor for Value-Only Property

When you call the System object, properties are specified as comma-separated pairs of Name,Value arguments or, if specified, Value-only arguments. Name is the property name and Value is the corresponding value. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Value-only arguments are useful for properties that are frequently set to nondefault values. For example, System objects that read a file often require the file name property to be reset.

Tip: Within the body of the constructor, do not assign property values. This practice can cause problems if you use the System object in multiple environments (such as in a System block, in a MATLAB script, and in generated code). Instead, use default property values or change values inside setupImpl.

Examples

expand all

Define a System object constructor that allows name-value pair input arguments.

Define a constructor for name-value pair inputs.

function obj = Counter(varargin)
    % Support name-value pair arguments when constructing object
    setProperties(obj,nargin,varargin{:})
end

With this constructor body, create a Counter object using name-value pairs.

myObj = Counter('StartValue',0,'UseIncrement',true);

Define a System object constructor with a value-only input property.

Define a constructor with 'StartValue' as a value-only property input. This constructor also allows name-value inputs.

function obj = Counter(varargin)
    % Support value-only argument for StartValue when instantiating
    setProperties(obj,nargin,varargin{:},'StartValue');
end

With this constructor body, create a Counter object using a value-only argument for StartValue and name-value pairs for other properties.

myObj = Counter(0,'UseIncrement',true);
Introduced in R2010a