Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我使用它的句柄操作绘图上的数据:
x = 1:10; y = sin(x); h1 = line(x,y);
但是,如果图形在脚本实际终止之前关闭,则执行此类操作会返回错误。
>>set(h1,'Color','green') % line is green ??? Error using ==> set Invalid handle object.
有没有办法在h1对它进行任何操作之前检查它是否是一个有效的句柄?
h1
您可以使用该ishandle函数首先检查图形句柄是否有效:
ishandle
if ishandle(h1) set(h1, 'Color', 'green'); end
更新:
对于较新版本的 MATLAB,句柄对象是实际对象,而不仅仅是数值。更好的选择是使用isvalid处理对象的方法:
isvalid
if isvalid(h1) set(h1, 'Color', 'green'); end
请注意, ishandle 有一个缺点,它还接受常见的数值,例如 0(=桌面句柄)和 1(=默认打开的第一个图形),它们通常也是有效的句柄,尽管可能不是预期的句柄。如果您尝试设置不存在的属性,您仍然会看到错误。
要处理这种情况,只需将代码放在异常处理块中:
try set(myHandle,propName,propValue); catch % do something useful... (recreate the GUI?) end