问题
I am trying to produce a figure in MATLAB with a popupmenu that changes the axes of a subplot. This works so far. But when saving the figure using File > Save, my handles get deleted and it shows me the following error message:
Error using struct2handle
Error while evaluating uicontrol CreateFcn
Error using handle.handle/set
Invalid or deleted object.
Error in popup_test/mimi (line 33)
set(h1,'XData', [0,8],'YData',[0,8])
Error while evaluating uicontrol Callback
It appeares, that when saving the figure, the handle h1 is deleted. It still is there as a number but ishandle(h1)
returns 0.
This is the code I have produced my figure with:
function popup_test2
figure;
a=magic(4);
h1=imagesc(a);
uicontrol(...
'Style', 'popup',...
'String', 'first|second',...
'Position', [20 340 100 50],...
'Callback', @popupfcn,...
'CreateFcn', @popupfcn);
function popupfcn(hObj,event) %#ok<INUSD>
% Called when user activates popup menu
val = get(hObj,'Value');
if val ==1
set(h1,'XData', [0,5],'YData',[0,5])
elseif val == 2
set(h1,'XData', [0,8],'YData',[0,8])
end
end
end
So far I have tried saving using saveas(gcf,'filename.fig')
(which didn't work) and hgsave
, which sounded promising, but I didn't know how to use it correctly...
回答1:
What you're missing is recreating h1
after loading the figure. This can be done using the following line of code:
h1 = findobj(gcf,'type','image');
findobj finds the handle of the plotted image- allowing you to change it as you like.
See final code:
function popup_test2
figure;
a=magic(4);
h1=imagesc(a);
uicontrol(...
'Style', 'popup',...
'String', 'first|second',...
'Position', [20 340 100 50],...
'Callback', @popupfcn,...
'CreateFcn', @popupfcn);
function popupfcn(hObj,event) %#ok<INUSD>
h1=findobj(gcf,'type','image');
% Called when user activates popup menu
val = get(hObj,'Value');
if val ==1
set(h1,'XData', [0,5],'YData',[0,5])
elseif val == 2
set(h1,'XData', [0,8],'YData',[0,8])
end
end
end
Please note that saving data/handles along with your figure should generally be done using guidata.
来源:https://stackoverflow.com/questions/25378680/saving-a-matlab-figure-and-keeping-all-handles