Darcy
Darcy

Reputation: 659

MATLAB: How to keep gcf handle indices constant when updating figures

I have a relatively complicated figure with lots of data on it. I am turning different datasets on and off using "visible" on/off commands depending on user input. However, the user can also add more lines to the plot. Unfortunately gcf handles seems to update axes and data after adding more plots. This means that the index for each handle changes as more plots are added.

Is there some way to keep the indices the same? Why does MATLAB sort handles backwards (e.g. first plotted figure is the last handle index)? To me, it would make much more sense if the first handle index corresponded to the first plotted dataset and so on.

Below is a simple example:

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

Upvotes: 1

Views: 90

Answers (1)

gnovice
gnovice

Reputation: 125874

A better option than depending on the order of child objects is to just build a vector of Line object handles yourself by capturing the output from the plot function, like so:

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

In the vector hPlots, for example, the handle for the black line will always be the second element.

Alternatively, if you don't want to store all the handles you can use the Tag property of the line objects to label each line with a unique string, then use findobj to find that handle when needed using the tag:

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

Upvotes: 3

Related Questions