MATLAB® does not call the class constructor when loading an object from a MAT-file. However, if you set the ConstructOnLoad
class attribute to true
, load
does call the constructor with no arguments.
Enable ConstructOnLoad
when you do not want to implement a loadobj
method, but must perform some actions at construction time. For example, enable ConstructOnLoad
when you are registering listeners for another object. Ensure that MATLAB can call the class constructor with no arguments without generating an error.
Attributes set on superclasses are not inherited by subclasses. Therefore, MATLAB does not use the value of the superclass ConstructOnLoad
attribute when loading objects. If you want MATLAB to call the class constructor, set the ConstructOnLoad
attribute in your specific subclass.
If the constructor requires input arguments, use a loadobj
method.
loadobj
MethodUse a loadobj
method when the class constructor requires input arguments to perform object initialization.
The LabResults
class shares the constructor object initialization steps with the loadobj
method by performing these steps in the assignStatus
method.
Objects of the LabResults
class:
Hold values for the results of tests.
Assign a status for each value based on a set of criteria.
classdef LabResult properties CurrentValue end properties (Transient) Status end methods function obj = LabResult(cv) obj.CurrentValue = cv; obj = assignStatus(obj); end function obj = assignStatus(obj) v = obj.CurrentValue; if v < 10 obj.Status = 'Too low'; elseif v >= 10 && v < 100 obj.Status = 'In range'; else obj.Status = 'Too high'; end end end methods (Static) function obj = loadobj(s) if isstruct(s) cv = s.CurrentValue; obj = LabResults(cv); else obj = assignStatus(s); end end end end
The LabResults
class uses loadobj
to determine the status of a given test value. This approach provides a way to:
Modify the criteria for determining status
Ensure that objects always use the current criteria
You do not need to implement a saveobj
method.