MATLAB: Is the figure still empty after copying another axis handle to it

figurehandlesplot

I have the following problem: I have a GUI where I want to update the displayed figure depending on the user's key selection. Therefore, I have to change the axis handle because I have different types (boxplot, scatter, histogram, image). So far, I reset the axis handle and assigned the new axis handle (I get this one from a structure that refers to invisible figures that where created and plotted before). Here's the code:
cla(SAxes.hImg(i),'reset')
SAxes.hImg(i) = copy(dAxesNew);
SImg.hImg(i) = copy(hplot); % contains properties from boxplot, scatter, histogramm...
As I want to switch back and forth, I don't want to delete the handles from the hidden figures, I only want to change the handle from the GUI figure. When I check the figures properties, the axis handle and the image handle but it's not displayed. The axis remains empty. What am I missing?
I created a simple version of my problem. Here's the code that you can run:
f2 = figure; % histogramm
histogram(rand(10,1),10);
f1 = figure; % image
imshow('peppers.png');
% task: display histogram in other figure by updating the axis handle
haxes = get(f1,'children'); % Axes handle

hplot = get(haxes,'children');
haxesNew = get(f2,'children'); % Axes handle
hplotNew = get(haxesNew,'children');
cla(haxes,'reset')
haxes = copy(haxesNew);
hplot = copy(hplotNew);
I'm only modifiying the code from another person. Normally, the changes are assigned to the global variables and the command
drawnow expose
updates the graphs. With images that show a 2D slice of an MRI image, it's no problem. Here the variable is assigned as follows:
set(SImg.hImg(i), 'CData', dImg); % with dImg is NxM matrix
dDim = [size(dImg, 2), size(dImg, 1)];
set(SAxes.hImg(i), 'Position', [SData(iSeriesInd).dDrawCenter.*dPos(3:4) - dSize./2, dSize], 'XLim' , [0.5 dDim(1) + 0.5], 'YLim' , [0.5 dDim(2) + 0.5]);

Best Answer

Since you're copying graphics objects from one figure to another, you want to use the copyobj function instead of copy. The copyobj function will handle changing the Parent of the copy it creates to the figure/axes/etc. into which you copied the existing graphics object. The copy function will not.