MATLAB: Copying all contents of a figure into another figure in Matlab GUIDE by clicking on a figure

guidematlab gui

I have two sets of axes: (axes1_1, axes1_2) and (axes2_1, axes2_2). When I click on either of the sets, I would like to plot them both on a larger axes set (axes_large1, axes_large2), as shown in the image below. If either axes1_1 or axes1_2 are clicked, the axes1_1 should be traced on axes_large1 and axes1_2 should be traced on axes_large2. Same would be the case when axes2_1 and axes2_2 are clicked.
Here is my code:
function plotMyImages(handles, data, depth, Score, flag)
if flag
h1 = handles.axes1_1;
h2 = handles.axes1_2;
else
h1 = handles.axes2_1;
h2 = handles.axes2_2;
end
cla(h1, 'reset');
im1 = imagesc(h1, 'CData', data, 'YData', depth);
set(h1, 'YDir', 'reverse'); box(h1, 'on');
xlabel(h1, 'Distance');
ylabel(h1, 'Depth') ;
cla(h2, 'reset');
im2 = plot(h2, Score, '*');
xlabel(h2, 'Distance');
appel = @show_in_figure;
set(im1, 'ButtonDownFcn', appel(flag)); % ButtonDownFcn modified to show figure on the larger axes
set(im2, 'ButtonDownFcn', appel(flag)); % ButtonDownFcn modified to show figure on the larger axes
The show_in_figure() is as follows:
function show_in_figure(hObject, event, handles, flag)
hfig = findobj('Type', 'axes', 'Tag', 'axes_large1');
copyobj(hObject, hfig);
xx = get(gca, 'XLim'); yy = get(gca, 'YLim');
set(hfig, 'XLim', xx);
set(hfig, 'YLim', yy);
xlabel(hfig, 'Distance');
ylabel(hfig, 'Depth');
hfig1 = findobj('Type', 'axes', 'Tag', 'axes_large2');
if flag
h1 = handles.axes1_2;
else
h1 = handles.axes2_2;
end
copyobj(h1, hfig1);
xlabel(hfig1, 'Distance');
Is there anything that I'm doing wrong here? I am using MATLAB 2018a.

Best Answer

(Caveat: I haven't tried running any of this code)
What are you expecting to happen when you set the ButtonDownFcn? It doesn't look like you're actually setting a function there, but are evaluating the function instead. Why not modify it like this?
appel = @(h,e)show_in_figure(h1,h2);
% ^^^ this capture the default inputs of a callback: the object handle (see doc:gcbo) and the event data
set(im1, 'ButtonDownFcn', appel); % ButtonDownFcn modified to show figure on the larger axes

set(im2, 'ButtonDownFcn', appel); % ButtonDownFcn modified to show figure on the larger axes
function show_in_figure(h1, h2)
handles=guidata(h1);
copyobj(h1,handles.handle_to_axes_large1)%copy image object to second axes

copyobj(h2,handles.handle_to_axes_large2)%copy image object to second axes
%if you want to copy the axis labels etc you can put that code here
end
Do not rely on gca inside GUIs, as you can always determine the handle. You can use gcbo and gcbf if you want, but you should never need findobj.
For general advice and examples for how to create a GUI (and avoid using GUIDE), have look at this thread.