Main Content

Initialize Properties and Setup One-Time Calculations

This example shows how to write code to initialize and set up a System object™.

In this example, you allocate file resources by opening the file so the System object can write to that file. You do these initialization tasks one time during setup, rather than every time you run the object.

Define Public Properties to Initialize

In this example, you define the public Filename property and specify the value of that property as the nontunable character vector, default.bin. Users cannot change nontunable properties after the setup method has been called.

properties (Nontunable)
  Filename = "default.bin"
end

Define Private Properties to Initialize

Users cannot access private properties directly, but only through methods of the System object. In this example, you define the pFileID property as a private property. You also define this property as hidden to indicate it is an internal property that never displays to the user.

properties (Hidden,Access = private)
  pFileID;
end

Define Setup

You use the setupImpl method to perform setup and initialization tasks. You should include code in the setupImpl method that you want to execute one time only. The setupImpl method is called once the first time you run the object. In this example, you allocate file resources by opening the file for writing binary data.

methods
  function setupImpl(obj)
    obj.pFileID = fopen(obj.Filename,"wb");
    if obj.pFileID < 0
       error("Opening the file failed");
    end
  end
end

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
    end
end

See Also

| |

Related Topics