Abhishek Bhatia
Abhishek Bhatia

Reputation: 9814

Plotting subplots from figures

I would like to iteratively create subplots from a figure. I have the following code:

for i=1:numel(snips_timesteps)
        x=openfig(sprintf('./results/snips/temp/%d.fig',i),'reuse');
        title(sprintf('Timestep %d',snips_timesteps(i)));
        xlabel('');
        ax= gca;
        handles{i} = get(ax,'children');
        close gcf;
    end
    h3 = figure; %create new figure
    for i=1:numel(snips_timesteps)
        s=subplot(4,4,i)
        copyobj(handles{i},s);
    end

Error I get is:

Error using copyobj
Copyobj cannot create a copy of an
invalid handle.



K>> handles{i}

ans =

  3x1 graphics array:

  Graphics    (deleted handle)
  Graphics    (deleted handle)
  Graphics    (deleted handle)

Is it possible to close a figure but still retain it's handle? It seems like the reference is being deleted.

Edit

    handles={};
    for i=1:numel(snips_timesteps)
        x=openfig(sprintf('./results/snips/temp/%d.fig',i),'reuse');
        title(sprintf('Timestep %d',snips_timesteps(i)));
        xlabel('');
        ax= gca;
        handles{i} = get(ax,'children');
        %close gcf;
    end
    h3 = figure; %create new figure
    for i=1:numel(snips_timesteps)
        figure(h3);
        s=subplot(4,4,i)
        copyobj(handles{i},s);
        close(handles{i});
    end

Error:

K>> handles{i}

ans = 

  3x1 graphics array:

  Line
  Quiver
  Line

K>> close(handles{i})
Error using close (line 116)
Invalid figure handle.

If I remove close(handles{i}) it plots the first figure again for all subplots!

Upvotes: 0

Views: 1013

Answers (1)

IKavanagh
IKavanagh

Reputation: 6187

No. By closing the figure you are deleting it and all of the data associated with it including its handle.

If you remove close gcf; and place figure(i); close gcf; after copyobj(handles{i},s); you will get the desired affect. However, you will also need to add figure(h3); before s=subplot(4,4,i) to ensure the subplot is added to the correct figure.

Here is some sample code to show you it working. It first creates 4 figures and grabs the handles to their axes it. Then we loop over each figure and copy it to the subplot of another figure.

for i = 1:4
    figure(i)
    y = randi(10, [4 3]);
    bar(y)

    ax = gca;
    handles{i} = get(ax, 'Children');
end

for i = 1:4
    figure(5);
    s = subplot(2, 2, i);
    copyobj(handles{i}, s);
    figure(i);
    close gcf;
end

Upvotes: 2

Related Questions