Main Content

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

The 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 Location and Year properties are ordinary properties whose values are saved when you save the object.

The 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:

  • The Chart property is Transient so the graphics objects are not saved.

  • ChartData is a private property that provides storage for the Bar object data (YData).

  • The load function calls the set.ChartData method, passing it the saved bar chart data.

  • The setup method regenerates the bar chart and assigns the handle to the Chart property. Both the class constructor and the set.ChartData method call setup.

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 setup method:

methods(Access = private)
   function setup(rf,data)
      rf.Chart = stairs(data);
   end
end

Related Topics