我有一个相对复杂的数字,上面有很多数据。我将根据用户输入使用“可见”打开/关闭命令打开和关闭不同的数据集。但是,用户也可以向绘图添加更多线。不幸的是,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
答案 0 :(得分:3)
比依赖子对象的顺序更好的选择是通过捕获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
property用唯一的字符串标记每行,然后在发生以下情况时使用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');