MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Set Property Values at Construction Time


This example shows how to define a System object constructor and allow it to accept
name-value property pairs as input.

Set Properties to Use Name-Value Pair Input

Define the System object constructor, which is a method that has the same name as the
class (MyFile in this example). Within that method, you use the setProperties method
to make all public properties available for input when the user constructs the object.
nargin is a MATLAB function that determines the number of input arguments. varargin
indicates all of the object’s public properties.

methods
function obj = MyFile(varargin)
setProperties(obj,nargin,varargin{:});
end
end

Complete Class Definition File with Constructor Setup

classdef MyFile < matlab.System
% MyFile write numbers to a file

% These properties are nontunable. They cannot be changed
% after the setup method has been called or while the
% object is running.
properties (Nontunable)
Filename ="default.bin" % the name of the file to create
Access = 'wb' % The file access character vector (write, binary)
end

% These properties are private. Customers can only access
% these properties through methods on this object
properties (Hidden,Access = private)
pFileID; % The identifier of the file to open
end

methods
% You call setProperties in the constructor to let
% a user specify public properties of object as
% name-value pairs.
function obj = MyFile(varargin)
setProperties(obj,nargin,varargin{:});

34 System object Usage and Authoring

Free download pdf