MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
Although not part of setup, you should close files when your code is done using them. You
use the releaseImpl method to release resources.

Complete Class Definition File with Initialization and 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 the object
% is running.
properties (Nontunable)
Filename = "default.bin" % the name of the file to create
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 (Access = protected)
% In setup allocate any resources, which in this case
% means opening the file.
function setupImpl(obj)
obj.pFileID = fopen(obj.Filename,'wb');
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

34 System object Usage and Authoring

Free download pdf