Depending on the requirements of your class, there are various ways you can use
loadobj methods. This pattern is a flexible way to solve problems that you cannot address by simpler means.
The basic process is:
saveobj to save all essential data in a
struct and do not save the object.
loadobj to reconstruct the object from the saved data.
This approach is not useful in cases where you cannot save property values in a
struct field. Data that you cannot save, such as a file identifier, you can possibly regenerate in the
For this pattern, define
saveobj as an ordinary method that accepts an object of the class and returns a
Copy each property value to a structure field of the same name.
You can save only the data that is necessary to rebuild the object. Avoid saving whole objects hierarchies, such as those created by graphs.
methods function s = saveobj(obj) s.Prop1 = obj.Prop1; s.Prop2 = obj.Prop2 s.Data = obj.GraphHandle.YData; end end
loadobj as a static method. Create an object by calling the class constructor. Then assign values to properties from the
struct passed to
loadobj. Use the data to regenerate properties that were not saved.
methods(Static) function obj = loadobj(s) if isstruct(s) newObj = ClassConstructor; newObj.Prop1 = s.Prop1; newObj.Prop2 = s.Prop2 newObj.GraphHandle = plot(s.Data); obj = newObj; else obj = s; end end end
load function encounters an error,
struct instead of an object. Your
loadobj method must always be able to handle a
struct as the input argument. The input to
loadobj is always a scalar.
loadobj can handle a
struct input even if you are not using a
GraphExpression class creates a graph of a MATLAB® expression over a specified range of data.
GraphExpression uses its
loadobj method to regenerate the graph, which is not saved with the object.
classdef GraphExpression properties FuncHandle Range end methods function obj = GraphExpression(fh,rg) obj.FuncHandle = fh; obj.Range = rg; makeGraph(obj) end function makeGraph(obj) rg = obj.Range; x = min(rg):max(rg); data = obj.FuncHandle(x); plot(data) end end methods (Static) function obj = loadobj(s) if isstruct(s) fh = s.FuncHandle; rg = s.Range; obj = GraphExpression(fh,rg); else makeGraph(s); obj = s; end end end end
Create an object with an anonymous function and a range of data as inputs:
h = GraphExpression(@(x)x.^4,[1:25])
h = GraphExpression with properties: FuncHandle: @(x)x.^4 Range: [1x25 double]
GraphExpression object and close the graph:
save myFile h close
Load the object. MATLAB recreates the graph:
load myFile h
load function cannot create the object and passes a
loadobj attempts to create an object with the data supplied.