"Handle to deleted figure" error - Matlab hg2 - Storing a figure handle in a class

2.3k views Asked by At

I have a class that stores a figure handle. With the new Matlab handle graphics hg2 I get a "handle to deleted figure" error.

classdef mytestclass
    properties
        hFig = figure
    end
end

Creating just one instance of the class works fine, I get a.hFig as a valid figure handle.

a = mytestclass % this will open the figure

But when I close the figure, and create another instance of the class, I get

b = mytestclass % this won't open any figure
b.hFig % this is now a handle to a deleted figure

Am I doing something wrong with classes? Or is this a bug?

1

There are 1 answers

0
Hoki On BEST ANSWER

I tried your example on Matlab 2009a (long before the new HG2) and the behavior is strictly the same as you describe.

it seems you are doing something slightly wrong with the way classes work in Matlab.

Basically you can assign the default value of a property with any type of numeric/text value:

properties
   myProp %// No default value assigned
   myProp = 'some text'; 
   myProp = sin(pi/12); %// Expression returns default value
end

but do not assign them with a handle to something

myProp1 = figure ;       %// all the object of this class will always point to this same figure
myProp2 = plot([0 1]) ;  %// all the object of this class will always point to this same line object

otherwise all the objects of your class (even newly created) will point to the same actual handle which was created only once when your first object was instantiated.

If you want to generate a different graphic object (figure) each time you create a new object of your class, you have to generate it in the class constructor.

So your class become:

classdef mytestclass
   properties (SetAccess = private) %// you might not want anybody else to modify it
      hFig
   end
   methods
      function obj = mytestclass()
         obj.hFig = handle( figure ) ; %// optional. The 'handle' instruction get the actual handle instead of a numeric value representing it.
      end
   end
end

from the help:

Initializing Properties to Unique Values

MATLAB assigns properties to the specified default values only once when the class definition is loaded. Therefore, if you initialize a property value with a handle-class constructor, MATLAB calls this constructor only once and every instance references the same handle object. If you want a property value to be initialized to a new instance of a handle object each time you create an object, assign the property value in the constructor.