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.

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{:});
end
end
methods (Access = protected)
% In setup allocate any resources, which in this case is
% opening the file.
function setupImpl(obj)
obj.pFileID = fopen(obj.Filename,obj.Access);
if obj.pFileID < 0
error('Opening the file failed');
end
end
% This System object writes the input to the file.
function stepImpl(obj,data)
fwrite(obj.pFileID,data);
end
% Use release to close the file to prevent the
% file handle from being left open.
function releaseImpl(obj)
fclose(obj.pFileID);
end
end
end