How can I check if a MATLAB handle is valid?
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 obje开发者_高级运维ct.
Is there a way to check if h1
is a valid handle before doing any manipulations with it?
You can use the ishandle
function to check first if a graphics handle is valid:
if ishandle(h1)
set(h1, 'Color', 'green');
end
UPDATE:
For newer versions of MATLAB, handle objects are actual objects, not just numeric values. The better option is to use the isvalid
method for handle objects:
if isvalid(h1)
set(h1, 'Color', 'green');
end
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
精彩评论