Save figure userdata to a workspace variable

26 次查看(过去 30 天)
I have assigned some the data and metadata (and some additional stuff) as 'Userdata' to a figure in order to assure that the graphic description of my data matches the actual data behind the graphics.
When I open the figure the original data are easily retrievable by:
graphdata = get(fig_handle,'UserData');
But, what I wish to do is to create a button in my figure which allows me to 'export' the userdata to workspace. Is that possible by creating/assigning a ButtonDownFcn to a pushbutton uicontrol? Preferably with a dialogue for naming the variable.
If possible I'd prefer assigning something generic to the ButtonDownFcn to assure that it works for other users even without access to my GIT or my local/personal functions.
fig_handle = figure;
myData.xData = rand(10,12000);
myData.yData = randn(10,1);
myData.sampleNames = {'Sample01','Sample02','Sample03','Sample04','Sample05',...
'Sample06','Sample07','Sample08','Sample09','Sample10'};
plot(myData.xData')
legend(myData.sampleNames);
set(fig_handle,'UserData',myData)
btn = uicontrol('Parent',gcf,'Style','pushbutton','string','Export userdata');
set(btn,'ButtonDownFcn',@somethingsomething)
savefig(fig_handle,'figure_with_myData.fig')
...i.e. what to do with the @somethingsomething in order for the button to extract userdata to a user defined variable in the base workspace.

采纳的回答

Geoff Hayes
Geoff Hayes 2020-4-1
Johannes - instead of using the ButtonDownFcn for the button, just use Callback. In this example, when the user presses the button, the callback fires and the userData is saved to a mat file (it can be adapted to save to the workspace if needed):
function FigureWithExportButton
fig_handle = figure;
myData.xData = rand(10,12000);
myData.yData = randn(10,1);
myData.sampleNames = {'Sample01','Sample02','Sample03','Sample04','Sample05',...
'Sample06','Sample07','Sample08','Sample09','Sample10'};
plot(myData.xData')
legend(myData.sampleNames);
set(fig_handle,'UserData',myData)
btn = uicontrol('Parent',gcf,'Style','pushbutton','string','Export userdata', 'Callback', @exportDataCallback);
function exportDataCallback(hObject, eventdata)
userData = get(hObject, 'UserData');
filename = [char(inputdlg('Please enter a file name:', 'Export UserData')) '.mat'];
save(filename, 'userData');
end
end
  1 个评论
Johannes Hougaard
Thank you Geoff.
That was really helpful.
I ended up using a slightly moderated version in order to stay clear of a 'personal' function (the exportDataCallback) as I generated the figure in a script rather than a function.
But this:
set(btn,'Callback',@(x,y)cellfun(@(varname)assignin('base',varname,get(get(x,'Parent'),'UserData')),inputdlg('Enter Variable Name')));
did the trick for me.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by