The primary reason for modifying the save and load process is to support backward and forward compatibility of classes. Consider modifying the save and load process when you:
Rename a class
Define a circular reference of handle objects where initialization order is important
Must call the constructor with arguments and, therefore, cannot use
The most versatile technique for modifying the save and load process is to implement
loadobj, and if necessary,
saveobj methods for your class. MATLAB® executes these methods when you call
load on an object of the class.
save function calls your class
saveobj method before performing the save operation. The
save function then saves the value returned by the
saveobj method. You can use
saveobj to return a modified object or a
struct that contains property values.
load calls your class
loadobj method after loading the object. The
load function loads the value returned by the
loadobj method into the workspace. A
loadobj method can modify the object being loaded or can reconstruct an object from the data saved by the class
saveobj method that modifies the object being saved, then implement a
loadobj method to return the object to the correct state when loading it.
loadobj method as a
Static method because MATLAB can call the
loadobj method with a
struct instead of an object of the class.
saveobj method as an ordinary method (that is, calling it requires an instance of the class).
MATLAB saves the object class name so that
load can determine which
loadobj method to call in cases where your
saveobj method saves only the object data in a structure. Therefore, the class must be accessible to MATLAB when you load the object.
loadobj method when:
The class definition has changed since the object was saved, requiring you to modify the object before loading.
saveobj method modified the object during the save operation, possibly saving data in a
struct. Implement the
loadobj method to reconstruct the object from the output of
When you decide to modify the default save and load process, keep the following points in mind:
If loading any property value from the MAT-file produces an error,
load passes a
struct field names correspond to the property names extracted from the file.
loadobj must always be able to accept a
struct as input and return an object, even if there is no
saveobj does not return a
saveobj returns a
load always passes that
Subclass objects inherit superclass
saveobj methods. Therefore, if you do not implement a
saveobj method in the subclass, MATLAB calls only the inherited methods.
If a superclass implements a
saveobj method, then a subclass can also implement a
saveobj method that calls the superclass methods. For more information, see Save and Load Objects from Class Hierarchies.
load function does not call the constructor by default. For more information, see Initialize Objects When Loading.