tags:

views:

463

answers:

2

I manipulate data on a plot using its handle

x = 1:10; y = sin(x);
h1 = line(x,y);

However, if the figure gets closed before the script actually terminates, doing something like this returns an error.

>>set(h1,'Color','green') % line is green
??? Error using ==> set
Invalid handle object.

Is there a way to check if h1 is a valid handle before doing any manipulations with it?

+4  A: 

You can use the ISHANDLE function to check first if a graphics handle is valid:

if ishandle(h1)
  set(h1,'Color','green');
end
gnovice
Jonas
+1  A: 

Note that ishandle has a drawback in that it also accepts common numeric values like 0 (=desktop handle) and 1 (=the first open figure by default) which are often also valid handles although possibly not the expected handle. You will then still see an error if you try to set a non-existent property.

To handle such cases, simply place your code within an exception-handling block:

try
   set(myHandle,propName,propValue);
catch
   % do something useful... (recreate the GUI?)
end
Yair Altman
A try/catch block is a good solution. However, the handle `0` is always reserved for the root object and plot objects or uicontrols always have floating-point handles. Figures have integer handles by default, but you can force MATLAB to use a floating-point handle for figures by creating the figure with the property 'IntegerHandle` set to 'off'. This will avoid the situation where a figure is created, the integer handle is stored, and then the figure is deleted and a new figure created with the same integer handle (so it's actually a different figure than the first handle refers to).
gnovice

related questions