简体   繁体   English

如何检查MATLAB句柄是否有效?

[英]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 object.

Is there a way to check if h1 is a valid handle before doing any manipulations with it? 在使用它进行任何操作之前,有没有办法检查h1是否是有效的句柄?

You can use the ishandle function to check first if a graphics handle is valid: 您可以使用ishandle函数首先检查图形句柄是否有效:

if ishandle(h1)
  set(h1, 'Color', 'green');
end

UPDATE: 更新:

For newer versions of MATLAB, handle objects are actual objects, not just numeric values. 对于较新版本的MATLAB,句柄对象是实际对象,而不仅仅是数值。 The better option is to use the isvalid method for handle objects: 更好的选择是对句柄对象使用isvalid方法:

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. 请注意,ishandle的缺点在于它还接受常见的数值,如0(=桌面句柄)和1(默认情况下是第一个打开的数字),它们通常也是有效的句柄,尽管可能不是预期的句柄。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM