Use transient properties to avoid saving what you can recreate when loading the object. For example, an object can contain component parts that you can regenerate from data that is saved. Regenerating these components also enables newer versions of the class to create the components in a different way.
YearlyRainfall class illustrates how to regenerate a graph when loading objects of that class.
YearlyRainfall objects contain a bar chart of the monthly rainfall for a given location and year. The
Year properties are ordinary properties whose values are saved when you save the object.
Chart property contains the handle to the bar chart. When you save a bar chart, MATLAB® also saves the figure, axes, and Bar object and the data required to create these graphics objects. The
YearlyRainfall class design eliminates the need to save objects that it can regenerate:
Chart property is
Transient so the graphics objects are not saved.
ChartData is a private property that provides storage for the Bar object data (
load function calls the
set.ChartData method, passing it the saved bar chart data.
setup method regenerates the bar chart and assigns the handle to the
Chart property. Both the class constructor and the
set.ChartData method call
classdef YearlyRainfall < handle properties Location Year end properties(Transient) Chart end properties(Access = private) ChartData end methods function rf = YearlyRainfall(data) setup(rf,data); end function set.ChartData(obj,V) setup(obj,V); end function V = get.ChartData(obj) V = obj.Chart.YData; end end methods(Access = private) function setup(rf,data) rf.Chart = bar(data); end end end
An advantage of the
YearlyRainfall class design is the flexibility to modify the type of graph used without making previously saved objects incompatible. Loading the object recreates the graph based only on the data that is saved to the MAT-file.
For example, change the type of graph from a bar chart to a stair-step graph by modifying the
methods(Access = private) function setup(rf,data) rf.Chart = stairs(data); end end