Main Content

避免重复搜索对象

当您搜索句柄时,MATLAB® 必须搜索对象层次结构以找到匹配句柄,这非常耗时。保存您以后要访问的句柄是更快的方法。数组索引通常比使用 findobjfindall 更快。

此对象创建 500 个线条对象然后在循环中调用 findobj

figure
ax = axes;
for ix=1:500
   line(rand(1,5),rand(1,5),'Tag',num2str(ix),'Parent',ax);
end
drawnow;
for ix=1:500
   h = findobj(ax,'Tag',num2str(ix));
   set(h,'Color',rand(1,3));
end
drawnow;

更好的方法是将句柄保存到数组中,并在第二个 for 循环中为数组建立索引。

figure
ax = axes;
h = gobjects(1,500);
for ix = 1:500
   h(ix) = line(rand(1,5),rand(1,5),'Tag',num2str(ix),'Parent',ax);
end
drawnow;
% Index into handle array
for ix=1:500
   set(h(ix),'Color',rand(1,3));
end
drawnow

限制搜索范围

如果搜索句柄是必需的,那么通过指定对象树的起始点来限制被搜索对象的范围。例如,将起始点指定为包含要搜索的对象的图窗或坐标区。

另一种限制搜索对象花费时间的方法是限制搜索的深度。例如,调用带 'flat' 选项的 findobj 可以将搜索限制为特定句柄数组中的对象。

使用 findobjfindall 函数搜索句柄。

有关详细信息,请参阅查找对象