Matlab GUI - Querying the User for Input (An example)
13 Feb 2008 Quan Quach 40 comments 6,182 views
Introduction
In many applications, the user must specify the input. In this tutorial, you will learn how to use the listbox component and the uigetfile command to create an attractive input interface. Specifically, you will learn how to create a GUI that will allow the user to select multiple files and display all the file names inside the listbox. I’ve done a similar example before in the basic processing tool, but I would like to go over this portion in a little more detail. Here’s a picture of the GUI:

The Example Files and Code
-
First, download the GUI skeleton here. Unzip the files and place them wherever you please. I also included 4 sample excel files that you can use to test the GUI.
-
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. -
Now, add the following code to addFile_pushbutton_Callback. As the name suggests, this is the callback that will add the files to the listbox. For this tutorial, the only file type that I allowed to be added were excel files (.xls).
%gets input file(s) from user [input_file,pathname] = uigetfile( ... {'*.xls', 'Excel (*.xls)'; ... '*.*', '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 more than one file selected at once, %then the data is stored inside a cell if iscell(input_file) == 0 %add the most recent data file selected to the cell containing %all the data file names inputFileNames{end+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) %notice the use of {}, because we are dealing with a cell here! inputFileNames{end+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);
-
Next, we need to add the following code to the deleteFile_pushbutton_Callback. This code will allow you to delete any files you may have accidentally added into the listbox.
%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 || isempty(inputFileNames)) 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);
-
Before we add any code to the final pushbutton, let’s make sure that what we have done so far works. Now, save your .m file and run the GUI. You should see the following GUI appear

-
Press the Add File(s) button. You should see the following dialog box appear. Select all of the files at once.

-
Now you should see the following on your GUI. The selected files will appear in the listbox! Try using the delete pushbutton to delete some of the files you selected.

-
Now that you can select the input files, it might be a good idea if we actually did something with them. So let’s add some code that will read the data! Go back to the m-file, and add the following code to the readData_pushbutton_Callback.
%get the current list of file names from the listbox inputFileNames = get(handles.inputFiles_listbox,'String'); for x=1:length(inputFileNames) %display the file name on the command prompt inputFileNames{x} %display the excel data on the display prompt xlsread(inputFileNames{x}) end
-
Now, run your GUI again, add the excel files, and press the read data button. You should see the output on the Matlab command prompt! I showed some of the output here in the following picture.

Download Source Files
Click here to download the source files.
This is the end of the tutorial.
40 Responses to “Matlab GUI - Querying the User for Input (An example)”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


hi,
Is it possible for the input we query from user to be displayed in workspace?
Since the GUI is being run with its on workspace, the data will not show up in the main workspace.
I think the command you’re looking for is
assigninGood luck!
Hello,
How can I just display the filenames only?
Also, If I had a drop down menu on the gui with 4 strings how can I store the first list of filenames to the first string on the drop down menu and then when I click another string,the listbox is empty ready for the next list of filenames?
One confused guy!!
Froggy,
When you use the command uigetfile in the following manner:
input_file contains the file name
pathname contains the path of the file name
So if you only want to display the input_file name, then use input_file instead of fullfile(pathname, input_file) within the code
Cheers Quan, I have done this now for the add function but when I select one file it works but if I select more, the files do not appear?
Thanks a lot, it’s very helpful !!!
Hi Quan Quach
that is perfect, how can I read a text file from a directory and folder which will be asked by user?
cheers
It didn’t work with me when I tried the code of inputFile_listbox, it told me ‘Cell contents assignment to a non-cell array object.’ for the instruction of :
inputFileNames{end+1} = fullfile(pathname,input_file);
Saeed, give this a try:
http://www.blinkdagger.com/matlab/parse-data
hi
i want to query the user to enter the name of the file and then i want the size of the file to be displayed, is that possible?
Thanks
Hi Quan Quach,
Your tutorials are excellent - the “listbox query for input” GUI is exactly what I need for my application. Your GUI works perfectly for me.
I adapted the GUI to (1) do calculations in the FOR loop, when the readData_pushbutton_Callback is issued and (2) use a Static Text component to display some calculated variables.
I have two questions / difficulties:
(1) I copied a non-GUI calculation-type MATLAB code into the body of the FOR loop of the readData_pushbutton_Callback. One of the command statements in the code (which is now part of the FOR loop) is “clear”. This command produces the following error AFTER the first iteration:
??? Undefined variable “inputFileNames” or class “inputFileNames”.
Originally, this calculation-type MATLAB code (non-object oriented) worked without problem, when it was not put in the GUI. Ideally, I would like to free up memory after each file is read in and the calculations are performed, for each loop iteration. Should I comment out “clear”, or should I be more specific with “clear”, e.g. “clear global” or “clear variable1, variable2,…”?
(2) I added a Static Text component (tag = microtimez_staticText) to your GUI to display a calculated variable (microtimez) from the read-in files.
c=num2str(microtimez);
set(handles.microtimez_staticText,’String’,c);
guidata(hObject, handles);
I added these three statements in the body of the FOR loop for the readData_pushbutton_Callback. I want the GUI’s Static Text component to display a new microtimez value after each file is read-in. However my Static Text component displays only the LAST value after the last iteration. Should I set a property of Static Text component, or is my guidata statement incorrect, or should I be using a different component (e.g. Edit Text or Activex) to display every FOR loop value on the GUI?
BTW, I appreciate your time and wonderful work.
cheers
Salem
I need to open a .txt file with numeric data and plot the result.
The file is opening and loading. How to plot it now?
sorry,open many .txt files in listbox and plot them
while running a gui, is it possible to plot different files on different axes.
you can specify the axes by
axes(handles.axesname)
substitute axesname with the axes you named it in GUI Buidler
Thank u for the reply. But i didn’t get it. sorry…
From the list of files in the listbox, i have to open a specific file and plot it.
I have error in the plot that i get since it did not match my data. If i have only one file in the listbox it is okay. If i have many files in the listbox, and i try to select one and readit and plot it there’s the problem.can u help?
hi…i need some help here…i want to open the excel file with macros using matlab…but i want it open same as i using conventional way to open it…is there have any code that can solve my problem…
@yop
by conventional you mean by opening Excel?
you can figure out the filepath of your excel file and use the following
!filepath/excel.xls
that should open it up. The ‘!’ is analogous to the windows ‘run’ command
what should i do if my GUI result ” ??? attempt to reference of non structure array ‘handles’..
From the list of files in a listbox, is there a way to know ,the selected file is which number on the list?
for my previous post, will this work?
val=get(handles.listbox,’Value’);
it worked…for the past post..
And another doubt…
I used two pushbuttons. One has to select previous file and plot it each time the button is pressed.
The other has to select next file and plot it each time the button is pressed.
I’m getting it once, since i passed the value of first file selected in the callbacks for both pushbuttons.
Can u help??
Thank u for all the tutorials…
I used handles to pass the value of selected file to both the pushbuttons.
It worked.
thx,the code worked for me but i need to use the answer (matrix) to work with it later. what should i do?
Hi, I have 5000 excel files (from the image captures). The excel file names are test1.xls to test5000 xls. Every excel file consists of 4 columns and X rows. The number of rows (X) is decreasing with filename increasing (X of test1.xls is higher than X of test5000.xls).
I only need information the number of rows (X) of every excel file (from test1.xls to test5000). For instance, the number of rows of test1.xls is 3000, test2.xls is 2990 etc. Could I use or generate a matlab routine(macro) to get all “X” information (from test1.xls to test5000.xls)?
Thank you very much
Surya
Hi Quan Quach
Your work is excellent.
These are very helpful to me. Thanks a lot for that.
But I have problem running this example. Here is the error message.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
??? Attempt to reference field of non-structure array.
Error in ==> inputGUI>addFile_pushbutton_Callback at 92
inputFileNames = get(handles.inputFiles_listbox,’String’);
Error in ==> gui_mainfcn at 75
feval(varargin{:});
Error in ==> inputGUI at 42
gui_mainfcn(gui_State, varargin{:});
??? Error while evaluating uicontrol Callback.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Please advise me.
Thanks
Please I am trying to develop a GUI on MATLAB that will solve for the FORCES in an n-membered Truss. I am done with writing the codes that will do the calculations. The problem I am having are:
1. Plot the Truss with the members number-label shown
2. I will like to include a group of 3-button with One button for Loading the forces at the nodes, another to load the supports’ coordinates, and the last one to load the nodes coordinates.
3. The processes in 2 I want it to be interactive such that when I a button it will bring an excel file inside which the data will be typed and read into MATLAB at the click of “OK”.
4. I want to return the an array of formatted output which consists of member number, Value of the Force on member, and nature of the force i.e compression or tension or none for zero force.
5. My greatest challenge is putting 4 on the GUI with the plot in 1
Please kindly help me out.
Hi all:
I just had a quick question about this “Matlab GUI - Querying the User for
Input (An example)” tutorial. I was wondering if there’s any way to select
multiple files from the list box. Now, when I open the files and they are
displayed in the listbox, I am not able to select more than one file in the
listbox (Ctrl+Click and Shit+Click don’t work here).
Thanks
Yasser
i really need help on my MATLAB GUI program. can anyone help me? please email me at intan_tassya@yahoo.com if you’re wiling to help me.
i’ve create a simple GUI interface. im using MATLAB V.7.2.. but i don’t even know how to input the function . for example, total_area= area1+area2 when we press the ‘calculate’ button. can anyone show me 1 clear example on this matter, i need to complete my project within 1 week starting from today…i’ve read all your comments etc, but i couldnt understand it.. besides, im importing the jpeg image into the axes which i labelled as ‘pic1′…when i generate, the picture will be displayed, but when i click the ‘next’ button, and trying to go back to the previous interface, the image gone. i dont understand why…please somebody, i really need help on MATLAB GUI…please email me..thank you very much
Tasya,
This beginner tutorial should help:
http://www.blinkdagger.com/matlab/matlab-gui-graphical-user-interface-tutorial-for-beginners
Quan
hi
the tutorial is very helpful indeed. but how can i do this modification:
lets say i have a blank table or a text box in the same figure, below the list box,
is it possible to displaying the data in that text box instead of the Matlab command prompt?
thanks
Hi,
do u noe how do i query the user for a folder/directory. So that i can get the directory pathname as an input for mi to manipulate in my function.
Thanks
Esther,
Try the following command:
uigetfile
uigetdir
Quan
Hi,
thanks alot. I manage to query for the folder. however, when i tried to get the string from an edit box using get(), i get the following error. May i noe wats wrong?
Error in ==> Main_GUI>push_start_Callback at 93
testFn=get(handles.edit_testfile,’String’);
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> Main_GUI at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==> guidemfile>@(hObject,eventdata)Main_GUI(’push_start_Callback’,hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
Thanks!
Hello..
Thanks for your tutorials, they are really helpful..
I am trying to read variables in MATLAB through GUI and I want to use them for further calculations. I might need them in other files. How can I do this?
Right now i have this code.
I have 5 variables to read so i hve 5 Static text and 5 edit text buttons.
I have added 1 push button which says enter and in the callback of ENTER i have added these lines:
output.data1=get(handles.data1,’string’) .
Could you please tell if this is right? and how can I store them? because I cant see the values which MATLAB reads in command line or so.
Hello.
When I select a listbox item with the mouse, it becomes blue highlighted, and I can move throgh the listbox with the keyboard arrow keys.
But when I push a button, like “Read Data” button, the listbox item becomes gray highlighted, and I can’t move with the keyboard arrow keys anymore unless I select an item again with the mouse.
Is there any way to highlight in blue an item after process it without using the mouse so that I can move with the arrow keys every time? I need to move through a listbox using the arrow keys, and in every move I want a file to be processed. In every move the file is processed and the highlight becomes gray, so I can’t move anymore with the arrow keys.
Can somebody help me? And sorry my English writting.
See you.
Hi-
Thanks for your tutorials. I’ve been finding them helpful and am still working through them.
I’m looking to create a program that starts by doing one of two things, either:
1) asking the user to select a variable from the workspace (which contains data)
or
2) input data from an excel spreadsheet, which will be stored as variable (which can be referenced later in the program)
the purpose of this user prompt is so that my program can effectively alter the data set the user inputs. I’m looking for the simplest possible way of accomplishing this. I don’t know if a GUI is more complicated than I need. But maybe it is the right direction. The GUI you just described seems perfect, only I don’t know how to properly reference the input I have just received from the user. Basically, what is the variable name that contains my data set that was imported from the excel spreadsheet? I understand the basics of the GUI, but I’m still not sure under what name my data set has ended up (so I can use it for the rest of my program). I’m kind of new at this. So thanks for your help. If you also have any ideas of a simpler way of going about this, let me know! Thanks!
- Mary
I just found your site today.Its simply great!!!
When i tried this example, i find this error! what might be the problem???
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
??? Attempt to reference field of non-structure array.
Error in ==> inputGUI>addFile_pushbutton_Callback at 92
inputFileNames = get(handles.inputFiles_listbox,’String’);
Error in ==> gui_mainfcn at 75
feval(varargin{:});
Error in ==> inputGUI at 42
gui_mainfcn(gui_State, varargin{:});
??? Error while evaluating uicontrol Callback.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Hi guys,
A bit of help using the Listbox in a GUI.
What I want to achieve is pretty simple but I’m getting these ridiculous errors and its driving me mad to debug. I want to make a simple GUI which will have a listbox and allow me to browse through directory structures and files. I have started with the sample GUI file lbox2.m/lbox.fig which comes with Matlab as a demo file for browsing directory structures and opening files. I have modified it to open and display CT dicom image files when double clicked and uptil here we’re working fine.
Now, after I have opened a few files and decided which is the right one, I want to press a push button which will start processing that particular image. For some reason, I cannot access the current listbox selection data in the push-button callback. If I try to save the filename in a handles structure, it gives me a error message saying that
guidata(hObject, handles); is not placed appropriately.
I’m having a hard time accessing the currently selected listbox data (filename or file index) in another pushbutton callback and I feel it’s just some syntax which I’m getting wrong.
Any help would be greatly appreciated. Thanks a lot.
Zubin.
I need help.. WHat is the code if i want to record the data in a window in a listbox in another window..?
Any help would be greatly appreciated. Thanks a lot.
god bless.
marvin