Matlab GUI Tutorial - Basic Data Processing Tool
26 Nov 2007 Quan Quach 43 comments 16,663 views
Add Files and Delete Files Callback Functions
The first two callbacks that we are going to program are addFiles_pushbutton_Callback and deleteFiles_pushbutton_Callback.
-
Add the following code under the addFiles_pushbutton_Callback:
%gets input file(s) from user. the sample data files have extension .s2p [input_file,pathname] = uigetfile( ... {'*.s2p', 'Data Files (*.s2p)'; ... '*.*', 'All Files (*.*)'}, ... 'Select files', ... 'MultiSelect', 'on'); %if file selection is cancelled, pathname should be zero %and nothing should happen if pathname == 0 return end %gets the current data file names inside the listbox inputFileNames = get(handles.inputFiles_listbox,'String'); %if they only select one file, then the data will not be a cell if iscell(input_file) == 0 %add the most recent data file selected to the cell containing %all the data file names inputFileNames{length(inputFileNames)+1} = fullfile(pathname,input_file); %else, data will be in cell format else %stores full file path into inputFileNames for n = 1:length(input_file) inputFileNames{length(inputFileNames)+1} = fullfile(pathname,input_file{n}); end end %updates the gui to display all filenames in the listbox set(handles.inputFiles_listbox,'String',inputFileNames); %make sure first file is always selected so it doesn't go out of range %the GUI will break if this value is out of range set(handles.inputFiles_listbox,'Value',1); % Update handles structure guidata(hObject, handles);
-
But what happens if you accidentally added too many files? This is what the delete button is for! Add the following code underneath the deleteFiles_pushbutton_Callback:
%get the current list of file names from the listbox inputFileNames = get(handles.inputFiles_listbox,'String'); %get the values for the selected file names option = get(handles.inputFiles_listbox,'Value'); %is there is nothing to delete, nothing happens if (isempty(option) == 1 || option(1) == 0 ) return end %erases the contents of highlighted item in data array inputFileNames(option) = []; %updates the gui, erasing the selected item from the listbox set(handles.inputFiles_listbox,'String',inputFileNames); %moves the highlighted item to an appropiate value or else will get error if option(end) > length(inputFileNames) set(handles.inputFiles_listbox,'Value',length(inputFileNames)); end % Update handles structure guidata(hObject, handles);
To allow multiple files to be selected within the listbox, you must add the following code to the opening function. Alternatively, you can change these properties through the Property Inspector using GUIDE.
set(handles.inputFiles_listbox,'Max',2); set(handles.inputFiles_listbox,'Min',0);
-
After you have added in the code, you should test the GUI to make sure that it works. There are some sample test files included in the zip file that you just downloaded. You can try adding/removing these files to the GUI. The menu below pops up when you click on the “Add Files” button.

43 Responses to “Matlab GUI Tutorial - Basic Data Processing Tool”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


Hi!
Thanks for a very clear tutorial. A lot of things I’ve learnt from this tutorial. Really appreciate it.
TQ,
zuri
I just want to say thanks a bunch!!! All your tutorials will help me and others like me gain knowledge and confidence in our jobs and lives. I’ll be sure to “pay it forward” your generosity.
Hello,
I’ve been working my way through these tutorials the last few days and they are excellent - far superior to the MATLAB manual on GUIs!
A question I have regarding the current tutorial. Is there a way to change the colours of the lines in the plots - ie a different colour for each testfile that is plotted.
Hello Jack,
I’m glad you found this tutorial useful.
You can change plot line colors using the following method
You should check the documentation on the plot command to get more details on this.
Quan
Hello Quan,
Wow what a quick reply - impressive!
Yes I have tried putting this command in. What I would like to do is have a different colour for each testfile rather than have them the same colour. In that way is it easier to identify the runs.
So TESTFILEA - Blue.
TESTFILEB - Red
TESTFILEC - Green
It is straight forward to do this in MATLAB with the raw data but it would be nice to do it in the GUI.
I have never used GUI before but following your tutorials I have gained far more information than the detailed but not very instructive MATLAB manual.
One way to do this is to define a cell array as the following:
Then, if you use a for loop to generate your plot, you can do the following:
Not sure if this is the best way, I’ll have to get back to you on this one.
If you’re using a for loop to cycle through data that you want to plot, and you want the curves to be different colors. You should use
instead of
holdHi Quan,
thanks for the help on uigetfile.
One thing that is still not working for me is that after i obtain the file path, I can’t use it. ie i save the file path as myFile, (it saves myFile as ‘C:\ etc’), but then when i try and run xlsread like this: m = xlsread(myFile, ’sheet’, ‘range’), it tells me that the filename needs to be a string. I thought it was already a string!
What am I doing wrong?
A separate unrelated question, each time i load my figure, I get the following error:
??? Error using ==> feval
Undefined command/function ‘inputFiles_edit_CreateFcn’.
Error in ==> gui_mainfcn at 75
feval(varargin{:});
Error in ==> ClassificationModelOne at 45
gui_mainfcn(gui_State, varargin{:});
??? Error using ==> struct2handle
Error while evaluating uicontrol CreateFcn
I don’t have a function called: inputFiles_edit_CreateFcn. I did at one point, but I have since removed it from the m file and from the design of the GUI. Is it hiding somewhere else that i don’t know about?
Hi Kate,
I have been scouting forums looking for an answer to the same question you posed above (2nd question). I have an error that seems to be the exact same as the one you described above in relation to a function ‘txt_CreateFcn.’ I have been developing this GUI for a few weeks so the only thing I can imagine that happened was that I accidentally typed in that name incorrectly at some stage for a text box and deleted it just as quickly. The problem seems to be that the GUI still looks for the CreateFcn for the deleted object. I inserted a ‘txt_CreatFcn’ at the end of my m file and the error disappeared.
Hope this helps,
Best of luck with the GUI.
Steve.
Hello,
I’ve a problem with the function savePlotWithinGUI when I save the plot with the extension *.fig. I can save the figure without problems, but when I’m going to open it, Matlab give me the next error:
Error using ==>open
Output argument “valid” (and maybe others) not assigned during call to “C\Archivos de programa\MATLAB71\toolbox\matlab\datatypes\isprop.m (isprop)”.
If I don’t save the legend, there ins’t any problem. But I need save the figure with the legend and extension *.fig.
I hope that you can help me.
Thanks.
Hi Isabel,
I just tried to recreate your error but I couldn’t. I saved the figure WITH the legend and it was able to open up fine on it’s on. I’m sorry I cannot help you here.
Quan
Thanks for your answer Quan.
Can you save the plot with the legend in a file *.fig? I’m continue with the same error, I can’t use twice the function copyobj, maybe, we are working with differents version of Matlab. I’m working with matlab 7.1.
Thanks
Hi Isabel,
I’m working with version 2007a. That might be the problem
Quan
Is there a way to recall the directory where the files were selected from if the working directory is elsewhere?
Thanks
Thank you for this tutorial.
Thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuu!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Quan, do you know how to make a Java wrapper for a GUI and put it on the web? I’ve seen that you need the Matlab compiler for Java (https://tagteamdbserver.mathworks.com/ttserverroot/Download/47137_91126v02_MATLAB_Build_JA.pdf), but I was wondering if there’s a way without having to buy the compiler.
Thank you very much!
Ana.
Halo Quan Quach
Wow amazingggg, it is very helpful for me in learning GUI……..You are such generous person in sharing your knowledge with others……
Btw I still have question concerning data processing. My boss asked me to do an animation of measurement data with matlab. I do it in simple way, just write it in Mfile. To make it more interactive, I decided to make it in GUI. But there is still one element that is not exist in your explanation. In my my animation I want to make a pause button, so someone can stop the animation for a while, and can continue again after pressing the button. I would be very thankful if you could give me a hint how to do that.
Thank you very much for your kindly help
Stefanus
Thank you for the tutorial. This example seems rather hard for me. If it is possible to publish the data process in seperate lessons again, like each .m file as a different class, it would be very nice.
Quan Quach
Wonderful tutorial! I’m learning alot from you excellent code and style.
I found as I was working through the export to Excel portion of you code that the magnitude was being output to both the magnitude and phase sheets. Scratching my head, I put a breakpoint in and found two places where the code needed to be changed to get the phase numbers output. I’ve copied your code below with the corrections and noted what the change is with a comment. I suspect that you put these “errors” in to see if people were really paying attention.
for x = 1:length(fileNames)
magnitudeData = [magnitudeData data{x}(:,2)];
phaseData = [phaseData data{x}(:,3)]; % ([phaseData data{x}(:,2)];)
magDB{x} = ‘Mag (dB)’;
phaseDegrees{x} = ‘Phase(Degrees)’;
end
saveFileName = fullfile(pathname, filename);
xlswrite(saveFileName,['Data File' fileNames],’Magnitude Data’,'A1′);
xlswrite(saveFileName,['Frequency (GHz)' magDB],’Magnitude Data’,'A2′);
xlswrite(saveFileName,magnitudeData,’Magnitude Data’,'A3′);
%Was (xlswrite(saveFileName,phaseData,’Magnitude Data’,'A3′);
Intended only to help and to demonstrate that I really am learning from your Tutorial.
Thanks again,
Dave
Great catch Dave! With all this code flying around I’m bound to make silly mistakes.
Quan
ya Great job……….thanks
but can u provide me the MATLAB source code for Penrose Tiling………
its very urgent……..plz help……..
guys,
i’m using GUI matlab for my project
i’ve created 2 editbox (user input) + 1 staticbox (sum) as interface, and a ‘calculate’ button..
i wanted to write a function in ‘calculate_callback’ so that the 2 editbox will add together and give result to the ’sum_box’.
what should i write under the ‘calculate_callback’??
Tasya,
you can use
val1=get(handles.edit1,’String’)
val2=get(handles.edit2,’String’)
valnum1=str2num(val1);
valnum2=str2num(val2);
total=valnum1+valnum2;
set(handles.sum,’String’,total)
hey,
Thank u very much for ur tutorial.its really helped me to get a knowledge about matlab.
hey I need help from u.I\\\’m University student.doing final year project(FYP) from matlab.I\\\’m going to do a \\\”Voice stress analyzer\\\” as my FYP.
I have some doubts about my matlab code.can u help me to figure it out?
take care
San
Hi Quan,
Excellent tutorial Sir .. It really opened my eyes to many hidden details.
My question: I keep getting an error mssg
“??? Cell contents assignment to a non-cell array object.”
when running a similar GUI as yours. After tracing the issue, I found that the code breaks when assiging fullfile (pathname, input_file) to inputFileNames{19} which is the evaluation of length(inputFileNames)+1 in addFiles_pushbutton_Callback function.
Summary:
code breaks here ..
“inputFileNames{length(inputFileNames)+1} = fullfile(pathname,input_file);”
Debug:
- fullfile(pathname,input_file) returns a valid location of path and file… Not the problem.
- inputFileNames = inputFiles_listbox .. No problem here either
- inputFileNames{length(inputFileNames)+1} evaluates to inputFileNames{19} .. Good to go
- inputFileNames{19} = ‘C:\path\file.ext’ … Problem!!
Any ideas why? Thanks in advance for your time.
Regards
Amino
Hi Amino,
The problem could be that when you use uigetfile, if you only select one file, it will be in the format of string. If you choose more than one file, it will be contained in a cell array.
Hopefully that answers the question.
Quan
Thank you for simple and useful tutorial Sir ..
Regards
Tayyar
Hi nice program . I have a question how i can get an extra column in my txt data that i have parsed using the function parsing data. I’ve tried a lot cant figure out please help.
thanks!
hii.
i want to add two value in Edit Text
for example ( 20 60)
thank
Hi, thanks for the great tutorial it has been very handy, however i am also trying to perform something else that i couldn’t find in any of the tutorials, wondering if you could end my sleepless nights
i am trying use a dataset called “trainIN” which i have imported into the workspace in a callback function like this
i need to feed it into a neural network but it is giving me an error
??? Undefined function or variable ‘trainIN’.
Error in ==> Credit_Score_Tool>trainbutton_Callback at 220
inputset = trainIN’;
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> Credit_Score_Tool at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==> @(hObject,eventdata)Credit_Score_Tool(’trainbutton_Callback’,hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
PLEEEASE HELP ME
Hi Arthur,
That’s a very common error one will see if you dataset isn’t available to your function. You may want to store your data set into your handles structure if you haven’t already.
Something early in your code like:
If your dataset is just in your command window workspace, the GUI probably won’t be able to reference that without extra help which I’m not sure how to do.
Hopefully that’s what you’re after.
-Zane
Hi, I’m trying to use GUI in Matlab to ask user key in some value, using looping method (I need few points of coordinate x and y and hence plot the 3D graph). Is there any way to store those data in an array or matrix without replacing the values?
Thanks.
if i wanto display a video or a sequence of frames then can i display on the axes? and can tell me how to do it? because i’m still new to GUI programming in MATLAB
thank you
Hello!
Your matlab material is very helpful to me..
Is it possible to import data(some parameters with values) from work space in the current directory & display it on GUI (static text or if any)??
THanks & Regrads,
Swetha….
Thanks for posting this tutorial. I’ve just started using MATLAB and I found this very useful indeed.
Hi, I’ll need you assistance. I Created a GUI to select an image to be displayed from a database. But I keep having problems in getting the value of the listbox uicontrol to be used by other callback functions.
function select_Callback (h_select, varargin)
% get the image of which folder to be displayed,
%folder = get (h_select, ‘Userdata’);
val = get(h_select, ‘Value’);
str = get(h_select, ‘String’);
%set (h_select, ‘Userdata’, str(val));
% set the choice as the case may be
% folder = str{val}
switch str(val);
case ‘f1′
%folder = ‘f1′;
set (h_select, ‘Value’, 1)
%set (h_select, ‘Userdata’, folder.val);
case ‘f2′
%folder = ‘f2′;
set (h_select, ‘Value’, 2)
case ‘f3′
set (h_select, ‘Value’, 3)
case ‘f4′
set (h_select, ‘Value’, 4)
case ‘f5′
set (h_select, ‘Value’, 5)
case ‘f6′
set (h_select, ‘Value’, 6)
case ‘f7′
set (h_select, ‘Value’, 7)
case ‘f8′
set (h_select, ‘Value’,
case ‘f9′
set (h_select, ‘Value’, 9)
case ‘f10′
set (h_select, ‘Value’, 10)
% set (h_select, ‘Userdata’, folder.val);
end
%set (f, ‘Userdata’, folder)
end
%————————————————————————-
function Illumination__Callback (h_illum, varargin)
% get the choice of image illumination to be displayed
val = get(h_select, ‘Value’);
str = get(h_select, ‘String’);
folder = str{val};
str = get(h_illum, ’string’);
val = get(h_illum, ‘value’);
% set the choice as the case may be
switch str{val};
case ‘Bright’
name = ‘bright’;
path = fullfile(dirloc, folder, name);
image = imread(path, ‘jpg’);
imshow (image)
case ‘Poor’
name = ‘poor’;
path = fullfile(dirloc, folder, name);
image = imread(path, ‘jpg’);
imshow (image)
case ‘Dark’
name = ‘dark’;
path = fullfile(dirloc, folder, name);
image = imread(path, ‘jpg’);
imshow (image)
end
set (f, ‘Userdata’, folder);
end
The error is
“cell contents reference from a non-cell array object.
Error in ==> fulldatabase>Illumination__Callback at 138
folder = str{val};”
It is unclear to me where to place the code for the handles that ‘enable’ and ‘disable’ the start_pushbutton. Does each handle go directly under the corresponding function? Can they be added on in one big chunk?
I’ve successfully worked through the more basic, related tutorials, but keep getting stuck at this point on basic_data_processing tool.
It’s been a while since there was a posting, but I hope someone can help. This is a great blog.
Thanks,
Helene
Hi Helene,
I try to troll the new posts and answer the questions that I think will help the most.
Where you put your commands matters very much. The automatically generated functions for your GUI try to be descriptive for when they get called, but aren’t always obvious. The main functions you’ll deal with/see are the _Callback and the _OpeningFcn/_CreateFcn. The latter 2 get called once your GUI first starts and builds those buttons, while the callback is the main function for whenever you button does some ‘action’ such as changing the number in an edit box, or pressing a pushbutton, or sliding the slider. Some of the functions have some commented code above them that try to describe when they get called as well (e.g. _OutputFcn).
The blinkdagger tutorials try to give good descriptions as to where the new code should go, but it’s not always obvious as to why.
Also, if you are referring to the enableButtons and disableButtons functions listed in this tutorial, note that those are specific functions made by Daniel/Quan from another tutorial that are being called in the function. You will need those functions accessible (either directly in the GUI, or in the same directory as your GUI files) to be able to use them. The code for the functions is given in Page 4 of this tutorial.
If you have any more specific questions, let us know.
GL,
Zane
Hi Zane,
Yes, the code on page 4 is precisely where I am getting stuck. I did complete that relevant tutorial with the enable and disable buttons of the 3 pushbuttons.
Under the start_pushButton_Callback, I enter ‘refresh(data_processing_tool)’ (line 13 on page 4 of this tutorial). However, in my m-file, the word ‘refresh’ does not turn BLUE as it does here. Does the word’s failure to change color mean I have the code in the wrong directory? I’d like to include the code on page 4 for these enable/disable functions directly into my basic_data_processing m file. This is what I am unsure of.
– Does every line of the code on p4 need to be entered? If so, I assume each one would be entered under the relevant component (figure1, start, reset, etc.)
– Does each “set function” then need to end with “enableButtons(handles);
guidata(hObject, handles);” ?
Thanks again. I seem to be at an incremental step in learning Matlab, and these tutorials have been great.
Helene
Helene,
Don’t worry about the blue text from the tutorials. That is just an incomplete design for the coding language used by the website. It should NOT turn blue in your .m file.
The enableButtons/disableButtons functions can be called (almost) anywhere in your GUI .m file. If you call a function somewhere in your .m file, it searches the list of possible functions, including anywhere in the main level of your GUI. I would just copy/paste the enable/disableButtons functions to the very end of your GUI. Make sure they are separate functions by following the vertical grey line immediately to the left of your written code. You should see that a new line stops/starts for each individual function.
The big block of text/code belongs only in ’start_pushbutton_Callback’ function, not in the enable/disableButtons functions.
All of the ’set’ commands should be left alone, no need to any any code after those. Those are all self-contained within the enable/disableButtons functions.
in short:
copy/paste the block of code at the very top (on p4) into the ’start_pushbutton_Callback’ function
copy/paste the enable/disableButtons functions into the end of your GUI .m file
I admittedly haven’t gone through this whole tutorial, but let me know if any questions/errors arise.
-Zane
Success!
Many thanks. By the way, “Pimp My GUI” was hilarious - made me LOL.
Any advice on if and when to transition to building GUIs without the generous help of GUIDE?
Helene
I still plan on using GUIDE for many years to come likely, but there are some good non-GUIDE tutorials here if you want to venture that way:
http://blogs.mathworks.com/videos/2009/08/06/gui-tutorials-from-the-file-exchange/