我有一个相对复杂的图形,上面有很多数据。我根据用户输入使用"可见"打开/关闭命令打开和关闭不同的数据集。但是,用户也可以向绘图中添加更多的线。不幸的是,gcf
句柄在添加更多绘图后似乎会更新轴和数据。这意味着,随着添加更多绘图,每个句柄的索引都会发生变化。
有没有办法保持指数不变?为什么MATLAB对句柄进行向后排序(例如,绘制的第一个图形是最后一个句柄索引(?对我来说,如果第一个句柄索引与第一个绘制的数据集相对应,这将更有意义,以此类推
下面是一个简单的例子:
figure
plot(1:10,'-r'); hold on
plot((1:0.2:4).^2,'-k')
h = gcf;
h.Children.Children(1); %The first index contains info for the black line
h.Children.Children(2); %The second index contains info for the red line
for i = 1:2
%Do stuff here where i = 1 is the last plot (black line) and i = 2 is the
%first plot (red line)
end
plot((1:0.1:2).^3,'-g')
h.Children.Children(1); %Now the first index CHANGED and it now represents the green line
h.Children.Children(2); %Now the second index CHANGED and it now represents the black line
h.Chilrden.Children(3); %Now this is the new index which represents the red line
for i = 1:2
%I want to do stuff here to the black line and the red line but the
%indices have changed! The code and the plots are much more complicated
%than this simple example so it is not feasible to simply change the indices manually.
%A solution I need is for the indices pointing to different datasets to
%remain the same
end
与依赖子对象的顺序相比,更好的选择是通过捕获plot
函数的输出来构建Line对象句柄的向量,如下所示:
figure;
hPlots(1) = plot(1:10, '-r');
hold on;
hPlots(2) = plot((1:0.2:4).^2, '-k');
hPlots(3) = plot((1:0.1:2).^3, '-g');
hPlots
hPlots =
1×3 Line array:
Line Line Line
例如,在向量hPlots
中,黑线的句柄将始终是第二个元素。
或者,如果你不想存储所有句柄,你可以使用行对象的Tag
属性用一个唯一的字符串标记每一行,然后在需要时使用findobj
使用标签找到句柄:
figure;
plot(1:10, '-r', 'Tag', 'RED_LINE');
hold on;
plot((1:0.2:4).^2, '-k', 'Tag', 'BLACK_LINE');
plot((1:0.1:2).^3, '-g', 'Tag', 'GREEN_LINE');
hBlack = findobj(gcf, 'Tag', 'BLACK_LINE');