Implementing saveobj and loadobj Methods
Implement a saveobj method that modifies the object being saved, then implement a
loadobj method to return the object to the correct state when loading it.
Implement the loadobj method as a Static method because MATLAB can call the
loadobj method with a struct instead of an object of the class.
Implement the 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.
Use a loadobj method when:
- The class definition has changed since the object was saved, requiring you to modify
the object before loading. - A 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 saveobj.
Additional Considerations
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 to loadobj. The 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 or saveobj does not return a struct. - If saveobj returns a struct, then load always passes that struct to loadobj.
- Subclass objects inherit superclass loadobj and saveobj methods. Therefore, if you
do not implement a loadobj or saveobj method in the subclass, MATLAB calls only
the inherited methods.
If a superclass implements a loadobj or saveobj method, then a subclass can also
implement a loadobj or saveobj method that calls the superclass methods. For
Modify the Save and Load Process