The Wayback Machine - https://web.archive.org/web/20110425193738/http://www.mathworks.com:80/help/techdoc/matlab_oop/br0lx_g.html
Skip to Main Content Skip to Search
Product Documentation

Modifying the Save and Load Process

Class saveobj and loadobj Methods

You can define methods for your class that are executed when you call save or load on an object:

If you implement a saveobj method that modifies the object being saved, implement a loadobj method to return the object to its proper state when reloading it. For example, you might want to store an object's data in a struct array and reconstruct the object when reloaded to manage changes to the class definition.

Implement loadobj as a Static Method

You must implement the loadobj method as a Static method because loadobj can actually be called with a struct or other data instead of an object of the class. You can implement the saveobj method as an ordinary method (i.e., calling it requires an instance of the class).

MATLAB saves the object's class name so that load can determine which loadobj method to call, even if your saveobj method saves only the object's data in an array and not the object itself.

Processing Objects During Load

Implementing a loadobj method enables you to apply some processing to the object before it is loaded into the workspace. You might need to do this if:

Updating an Object Property When Loading

In the following example, the loadobj method checks if the object to be loaded has an old, shorter account number and calls a function to return an updated account number if necessary. After updating the object's AccountNumber property, loadobj returns the object to be loaded into the workspace.

methods (Static = true)
   function obj = loadobj(a)
      accnb = a.AccountNumber;
      if length(num2str(accnb)) < 12
         a.AccountNumber = updateAccountNumber(accnb); % update object
      end
      obj = a;  % return the updated object
   end
end

In this case, you do not need to implement a saveobj method. You are using loadobj only to ensure older saved objects are brought up to date before loading.

The Save and Load Applications section provides an example in which loadobj performs specific operations to recreate an object based on the data returned by saveobj during the save operation.

Save and Load Applications

The following sections describe some specific applications involving the saving and loading of objects.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A; sessions led by MATLAB experts.

 © 1984-2011- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS