Useage of plot handles as properties of a matlab class

10 views (last 30 days)
Hi,
i have built a matlab class that should be able to plot live data.
In order to do this it creates a new figure and several plots inside this figure.
My first question is: Is this a good idea to use plot handles as properties of a class? I have not a found a single example to do this. Note: I need the handles later in order to modify the data displayed in the plots.
My second question is (see reduced class code below): Why does matlab delete the first handle hPlot1 when another plot is created? At least the error message i get suggest this is happening.
classdef livePlot
properties
...
hPlot1
hPlot2
hFig
end
methods
%Constructor
function obj = livePlot(...)
...
obj.hFig = figure('Position',[50, 50, 550, 550]);
obj.hPlot1 = plot(obj.plotTime,obj.plotData1,'b');
set(obj.hPlot1, 'LineWidth', 1.5); % works fine
get(obj.hPlot1) % works fine
obj.hPlot2 = plot(obj.plotTime,obj.plotData2,'r');
get(obj.hPlot1) % error:
% Error using ==> get
% Invalid handle object.
end
end
end
I appreciate your help! Any hints in the right direction are welcome!
Cheers, Martin

Answers (1)

Guillaume
Guillaume on 27 Apr 2015
Edited: Guillaume on 27 Apr 2015
It's certainly not a problem storing graphic handles in a class. The only tricky bit comes with saving and loading objects to/from disk since you would have to recreate the graphic objects when an object is reloaded. I.E. you would have to overload loadobj to recreate the object properly. That is if you actually care about saving objects to disk (in a mat file for example).
As for your second question, the same error happens if you take the code out of the class. You're probably missing a hold on in your code. Without it, creating a new plot deletes the old one.
With the snippet of code you've shown (where there's only a constructor that only creates handles) it does not matter, but my feeling is that you would be better off with making your class itself a handle class:
classdef liveplot < handle
  2 Comments
Constantine Samios
Constantine Samios on 28 Jul 2018
Hello. Is there a solution to your first paragraph above? I am attempting to save a figure as a class property, but have trouble recreating the figure as once the original figure is closed, the handle points to a deleted object. Thanks!
Walter Roberson
Walter Roberson on 28 Jul 2018
If you need to be able to recreate the figure after it has been closed, you need to save(), or savefig(), or saveas() with 'fig', and then load the figure back from disk.
Alternately, you can keep enough history about what went into creating the figure to be able to reproduce it by running appropriate code.

Sign in to comment.

Categories

Find more on Specifying Target for Graphics Output in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!