Save Object Data to Recreate Graphics Objects
What to Save
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.
Regenerate When Loading
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:
Transientso the graphics objects are not saved.
ChartDatais a private property that provides storage for the Bar object data (
loadfunction calls the
set.ChartDatamethod, passing it the saved bar chart data.
setupmethod regenerates the bar chart and assigns the handle to the
Chartproperty. Both the class constructor and the
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
Change to a Stairstep Chart
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