Matlab GUI - Saving and Loading GUI Data
06 Feb 2008 Quan Quach 46 comments 6,406 views
Introduction
In this tutorial, you will learn how to save data from your GUI, and how to load it back in. This is a useful feature when you want your GUI to “remember” a group of settings. In addition, this gives you the chance to go back to previous states. The example we will use in this tutorial involves the slider GUI that was created in the Slider Tutorial. Here is a quick look at the finished GUI.

The Example Files and Code
-
First, download the GUI skeleton here. Unzip the files and place them wherever you please.
-
Now, type
guideat the command prompt.
-
Choose to open the sample GUI by clicking on “Open Existing GUI”. Click on “Browse” to locate where you saved the GUI files.

-
Here is what the GUI should look like when you open it:

-
Click on the
icon on the GUI figure to bring up the accompanying .m file. -
Let’s add some code to each of the pushbuttons. First, lets add the code for the save button.
Find the save_pushbutton_Callback and add the following code
%allow the user to specify where to save the settings file [filename,pathname] = uiputfile('default','Save your GUI settings'); if pathname == 0 %if the user pressed cancelled, then we exit this callback return end %construct the path name of the save location saveDataName = fullfile(pathname,filename); %saves the gui data hgsave(saveDataName);
-
Next, we want to add the following code to the load_pushbutton_Callback:
%allow the user to choose which settings to load [filename, pathname] = uigetfile('*.fig', 'Choose the GUI settings file to load'); %construct the path name of the file to be loaded loadDataName = fullfile(pathname,filename); %this is the gui that will be closed once we load the new settings theCurrentGUI = gcf; %load the settings, which creates a new gui hgload(loadDataName); %closes the old gui close(theCurrentGUI);
-
You might have noticed there were more callbacks, but you can ignore those for now. Let’s run the GUI! You should see the following GUI appear when you run it:

-
Now, lets move the slider all the way to the right, like this:

-
Now, let’s save the GUI’s current state. Press the “Save GUI Settings” button. The following window should appear, asking where to save the GUI data.

-
Next, move the slider to any arbitrary location. Now, click on the “Load GUI Settings”. Choose the same file that you just saved.

-
You should see a brief flicker, and the GUI should be restored to exactly how you just saved it seconds ago. If you moved the GUI to another location on the screen after the save, it will be sent back to the position it was at when you saved it!
-
You probably noticed the menu on the upper left of the GUI. If you don’t know how to create a custom menu, I suggest you visit this tutorial first. Anyhow, we can go back to the m-file and add in some code for the menu item callbacks. I prefer to use menu items sometimes because they help keep the GUI looking clean and uncluttered.

Copy the same code from the save_pushbutton_Callback to the saveSettings_Callback.
Similarly, do the same for load_pushbutton_Callback and loadSettings_Callback.
-
Now run the GUI again, and try using the menu instead. It should work exactly the same! In addition, you can even try the hotkeys, (Control + S) to save, and (Control + L) to load.
Download the Source Files
Click here to download the source files.
This is the end of the tutorial.
46 Responses to “Matlab GUI - Saving and Loading GUI Data”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


Thanks for the tutorial
Ur tutorial had helped me alot..but i’m facing problem tat i run a function that generate matrix in my GUI m.file.then the marix is double complex.how do i save it? coz it jz run and doesn’t appear in workspace..thx
Jenn
if you save the matrix in the handles structure, it will still be there when you save and add.
so for example, you would want to add this line of code somewhere:
handles.myMatrix = yourMatrix;
If you don’t save the matrix within the handles structures, it will only be available within the function where it is defined (also referred to as a local variable).
So to reiterate, store the matrix into your handles structure and it should work.
Hi, I’m very new to guis, and I’ve already learned much from your tutorials..
I want to be able to save gui generated data using the user’s name, so before any action can be taken on a gui i would like to have a variable called name either created with
name=input(’name ‘,’s’)
or
name=inputdlg(’name ‘,)
name=char(name);
my program allows for an ‘n’ amount of a pushbutton press, each time it updates a data file
I just dont know where to place this without having it be on the last pushbutton call back where the data is stored, ive tried placing it at opening but am encountering invalid handle errors or having it regenerate after any action on the gui interface. I want it to only ask once, at the beginning, and recall it on my last pushbutton callback.
Any help would be very much appreciated!!
THANK YOU
Quan…thanks for the tutorials
I’m doing my industrial training now, and all the tutorials has helped me greatly during the development of the project’s GUI development…
I’m gonna stay tuned for your next tutorial about MATLAB GUI…
quick question,
how do you load a figure inside an axes?
I used your “load settings” code to open the file, but it always load a blank axis…any help?
here’s the code
[filename, pathname] = uigetfile(’Choose the GUI figure to load’);
loadFigure = fullfile(pathname,filename);
axes(handles.axes6);
image(loadFigure);
axis off
use imshow instead of image
Great site! Just found it yesterday and it’s very intuitive and helpful. Have a question for you or your viewers:
I have a GUI where the user a) selects a file and b) enters values in 8 edit boxes. I use the hgsave function inside the okButton callback so that those values are there next time the user starts the gui. The problem is that the values in those edit boxes, and the filename they had selected, are not being passes to my main program like they do when I re-enter the values manually.
How do I re-assert those values so they can appear in the workspace (I use ‘assignin’) when the user just clicks OK and use the default (previously saved) values? thanks for any help.
Hi Justin,
How are you calling the 8 variables and the filename?
In the OK button callback, I am assumiing that the 8 variables and the filename will be used.
In this callback, you can do the following:
This way, you will be extracting the data directly from the edit text boxes.
I guess I would need a bit more information to really help you with the problem. How is the data being passed to the main program? Is the main program the actual GUI? More information would be helpful!
Quan
I just got it working by repeating my variable assignments in the _CreateFcn functions. This way at startup, all the variables are pre-defined. I do like your method though. It’s half the code and is cleaner in the sense that variables are only set once at the end when the OK button is pressed, not every time a value is changed in the gui. I will try it your way also. thanks!
My main program has all my data processing. I just recently created this gui to capture initial parameters. I call the gui at the start of my main application, then in the gui I use the ‘assignin’ function to place the variables in the main workspace. Then i delete the figure and the main program continues to completion.
It works great now, though a minor bug is the OK button starts out depressed every time and I can’t get it to “pop back out”. I tried setting the value to zero but it doesn’t seem to work. There wasn’t a _CreateFcn for the button by default. It still functions though, and that’s what matters.
Justin,
Glad you got it working!
Quan
I have created a GUI that has a user enter several pieces of information data which I will use to run some code. An example of the user input is below:
I have another function called where I am trying to pass X1 to. When I type in X1=handles.X1 I get a totally different number than was entered, off by a magnitude of 10.xxx. I am just lost on how to get my data out, my data just doesn’t seem to be available for recall. Any help would greatly be appreciated.
Hi Jesse,
If you’re calling the function within one of the callbacks, you can just do the following within your GUI callback:
Hello
I’m doing a proyecto at school, topografy - geodesy in matlab and your webpage has actually saved my live!
But I have a problem with saving my data in a vector. I want to use the same “edit” over and over again and save it in a vector. Simply explaned, I want my program to do topografic calculation called “itinerario”. The program askes at the begining how many points we have. Then I need the program to use the same edit (6 for every point, six vectors) and save every variable in a vector outside the function so I can use it in another function. The vector needs to have a flexible size depending on how many points there are. So every time I push “next point” button I need it to save what I wrote and give me a change to write a information about the new point. I’ve tried to use global, hObject.dummyVector and all kinds of things but somehow it doesn’t work
The vector never saves the variable from the input before.
Is there a posibility you can help me with this?
Katrin,
It looks like you want to share data between different functions within your GUI.
Try this tutorial:
Anyhow, i’ll try to explain a little bit here.
http://www.blinkdagger.com/matlab/matlab-gui-tutorial-sharing-data-among-callbacks-and-sub-functions
Inside your opening function, I would do the following:
Now, inside your next point callback:
It worked! Thank’s ! It helped alot and I really appreciate it.
Hi,
I’m new to creating the GUI and I was dissapointed to find out that when you run the GUI, the data aren’t saved automatically to the MATLAB workspace. In this tutorial you showed how to save the data, given the user specify where to save it to. Is it possible for the data to be saved automatically into MATLAB workspace once the GUI is run ?(the same as if the m.file program was run normally). Your help would be very much appreciated. Thank you.
Hi,
I have a problem, I am using the uigetfile and uiimport to load a dataset file. after loading the dataset file I would like the output of the dimensions ie rows and column.
with the following code I am getting the wrong dimensions……..
Your help would be very much appreciated. Thank you.
Hey Quan!
Your tutorials have been instrumental in furthering my matlab knowledge! But…I made a mistake, and don’t know how to go back.
I made a gui that will load a data file, allow me to select certain data series from a pop up menu, and plot them on an axes within that figure. The problem is that I wanted to get fancy, and I added a toolbar to be able to manipulate the figure. Toolbar works great, except that when I included the ’save’ button, it isn’t bringing up a dialog to save the axes (as I had anticipated), but rather saving the configuration of the entire figure. So all the data I had loaded, and any series that I had plotted on the axes in that figure all got saved as part of the ‘figure’. Now when I open my figure, my data is already loaded, and plots are showing up on my axes.
Any idea how I can revert back to my original settings? ie: how can I delete the loaded data, and the plotted data and then re-save the figure (I think that’s all I have to do right??) I think that the data gets loaded somewhere during the CreateFcn for the gui, and other matlab functions that are called from that which you rarely ever see. Please help!
Thanks in advance!
(next time ill just use the save plot routine from your site instead of the save ‘figure’ toolbar button)
Hey Quan, I’m pretty sure I figured it out. Couldn’t have done it without this awesome site though! Thanks!
Hi
I am using deploytool to make exe of my complete project. But there is an error in compilation because “save” command is not woring in exe while it is working in matlab although “load” commad works properly.
I am using ’save’ to update a .mat fle.
Kindly help.
hi
im trying to load values from edit box to matlab workspace, i was wondering if someone could help me with that. thanks in advance.
@moe
Try the ASSIGNIN command. This will allow you to save variables from a GUI into the main workspace.
Quan
cool example! thanks
but i have a question now , is it possible to change the GUI data directly on the old GUI.just like refresh. whtiout creating a new GUI?
How to do similar for saving a selected image to a path that I precise. Please I need help on this question!
I understand it saves your gui to the specified path.
But I want to do an open dialog to select a file and when I press save button to save me in the path I desire!
Here is what I’ve done in my callback:
On my form I have only a pushbutton to select the file and when pressing save to save my file in the folder I specified.
Any help would be appreciated!
function pushbutton1_Callback(hObject, eventdata, handles)
Im=handles.Image;
[pathname,filename] = uiputfile({’*.jpg’;'*.bmp’;'*.jpg’;'*.png’;'*.tif’;'*.gif’;'*.*’},’save as’) ;
imwrite(fullfile(pathname,filename))=Im;
guidata(hObject, handles);
So I simply need to select an image file and store him on a path that I select.
Thanks in advance!
Sry here is the code:
function pushbutton1_Callback(hObject, eventdata, handles)
Im=handles.Image;
[pathname,filename] = uiputfile({’*.jpg’;’*.bmp’;’*.jpg’;’*.png’;’*.tif’;’*.gif’;’*.*’},’save as’) ;
imwrite(fullfile(pathname,filename))=Im;
guidata(hObject, handles);
Mihaispr,
Is the issue that your current code is causing you problems?
If it is, I would guess you need to change your imwrite line and just drop the uiputfile line. IMWRITE does the saving for you; you just need to specify the file name, location, and format.
The syntax for IMWRITE is:
Good Luck,
Zane
hye…
i’m new in GUi..
can anyone teach me..
i have 2 buttons.. one for load a wav file.. 2nd one is to play the wav file.. for loading file n showing the waveform figure i follow yor coding.. but when comes to the play button.. i cant get it…
En olyan excell formaban szeretnem kiirtani a matrixot.. hogy kell?
Hi,
How can I fetch variables from the workspace into my GUI?
@Dan: have a look into assignin and evalin
Hello,
I would like to know, if its possible to do the loading with a pop-up menu?
So from the pop-up I can choose quickly the user-defined settings, and they will be automaticly assigned to my sliders.
And is there a way to save into the pop-up items list?
Thanks!
how to get data from workspace into gui figure text boxes
HI
PLEASE HELP FRİENDS
HOW CAN I MATRİS PROCESS. I DON’T KNOW TO WRITE FUNCTION?
hey.. im having trouble… i have a gui that opens another gui.. and i want to save the information that the user inputs on the second gui..
my problems are:
1) if i try to save the gui in a seperate folder inside the matlab folder, it cant find the file, it only works if i save it directly into the matlab folder.
how do you make the save window open directly to the folder you want to save it in.. and how do you get the open to read that file.
thanks guys!!
dear frds
please help me in resolving two issues
(a) how to create a tabular data and use of that data value in my gui m file coding
(b) how to save the data entered in gui/guide form
regards
rks
dear frnds
how to extract eb/no value from a given ber for bpsk scheme using matlab command
say ber= .5 * erfc {(eb/no)^.5 }
so if ber is 10^-6 what command to give in matlab for extracting eb/no.
rks
I’m a newbie in MATLAB. I wanna build a GUI like this. Enter 3 values for a triangle, check what form it is (ex:isosceles triangle,equilateral triangle…) and calculate it’s P, S. But in the first step, there’s a problem in my code. Even I try to enter invalid value for a triangel, the text appears in the staticedit still be : “This is a triangle”. Please help me.This is my code:
Please hepl me. I don’t know where’s the mistake.
NGHIA,
To have a triangle, you want the sum of any 2 sides greater than the 3rd side. You’ve got squared values which is useful for good ol’ Pythagoras, but not in this case. Get rid of the ^2 and it looks like everything else should work ok.
-Zane
Thanks so much Zane Montgomery. It’s mean I will mend my mistake is:
if a+b>=c||b+c>=a||a+c>=b…
Is that ok?? Please help me. Thank you
T_T. I’ve just mend my mistake but it keep answer : This is a triangle.
if a+b>=c||b+c>=a||a+c>=b…I’ve done my work.hehehe THANK QUAN and Zane Montgomery for this helpful site
how to manipulate data in one gui popupmenu from command in another gui
I’m trying to get some data in matrix form into the workspace. This code allows the gui fire up the file import browser. But when all the mousing is done, and the desired file has been selected, there is nothing in the workspace, and the workspace does not know what “handles” is.
I could more easily just execute uiimport from the command line and get where I want to go, but the customer wants it dumbed down with a gui.
I am beginning to think that programming a gui in Matlab is a big waste of time. There is almost no documentation on how to tweak the autogenerated gui code to get it to do what I want.
@Workerbee
When you run a function (from a GUI or other .m file), your variables are local to that function and only get passed if you declare an output (which is why no variables, including ‘handles’, is visible in the workspace). GUIs are a little less straightforward when declaring an output.
For this situation, I recommend looking into assignin function.
Syntax:
ws is the workspace you want to export to. For almost all applications, you’ll want to use ‘base’ as your ws. And if you want to keep the variable the same name, I assume just make ‘var’=val.
e.g.
your new variable will be in your workspace in the same format as it was in the GUI.
I found this from the MATLAB Central blogs. It’s a very good resource.
Don’t give up on MATLAB!
-Zane
dear frds
i have a problem in one of the logical statements of programme
elseif (handles.metricdata.channel == ‘AWGN’& handles.metricdata.scheme == ‘MPSK’& double(handles.metricdata.modorder) == ‘16′);
when i ma running the program it says input must be of equal size. if anyone can suggest soem other way of comparing
thanx in adv