MATLAB:更新图形时如何保持gcf句柄索引不变

MATLAB:更新图形时如何保持gcf句柄索引不变,matlab,matlab-figure,figure,Matlab,Matlab Figure,Figure,我有一个相对复杂的数字,上面有很多数据。根据用户输入,我使用“可见”开/关命令打开和关闭不同的数据集。但是,用户也可以向绘图中添加更多线。不幸的是,gcf句柄似乎在添加更多绘图后更新轴和数据。这意味着每个句柄的索引会随着添加更多绘图而更改 有没有办法保持指数不变?为什么MATLAB会向后排序句柄(例如,第一个绘制的图形是最后一个句柄索引)?对我来说,如果第一个句柄索引对应于第一个打印的数据集,那么它将更有意义,依此类推 下面是一个简单的例子: figure plot(1:10,'-r'); ho

我有一个相对复杂的数字,上面有很多数据。根据用户输入,我使用“可见”开/关命令打开和关闭不同的数据集。但是,用户也可以向绘图中添加更多线。不幸的是,
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

与依赖子对象的顺序相比,更好的选择是通过捕获函数的输出,自己构建线对象句柄的向量,如下所示:

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
中,黑线的句柄始终是第二个元素

或者,如果不希望存储所有句柄,则可以使用线对象的来使用唯一字符串标记每条线,然后在需要时使用标记来查找该句柄:

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');

您还可以将
findobj
与其他属性一起使用,例如
findobj(gcf、'Type'、'line'、'Color'、'k')
返回所有黑线的句柄。