Matlab GUI Tutorial - Basic Data Processing Tool

26 Nov 2007 Quan Quach 45 comments 18,094 views

Introduction
This tutorial outlines the basic skeleton for a data processing GUI. The tutorial provides you with the visual aspect of the GUI via download, and then goes on to provide the code to each component callback. This tutorial draws upon many of the basic GUI elements: adding files to a listbox, parsing data, plotting data onto the GUI, saving GUI plots, disabling/enabling buttons, exporting data to Excel format, and many other things. If you just want to see the finished product, you can download the source files here. The source files include the GUI files, the m-files for the sub functions, and 3 sample data files. You can play around with this GUI to learn more about how GUIs are designed and coded. You can also use this GUI as a foundation for developing more advanced GUIs. I highly encourage that you take the time to look through the source code, and to hack it to your content. Feel free to modify it so that it suits your purposes.

This tutorial is written for those with a good amount of experience creating a Matlab GUI. If you’re new to creating GUIs in Matlab, you should visit this tutorial first. Basic/Advanced knowledge of Matlab is highly recommended. Matlab version 2007a is used in writing this tutorial. Both earlier versions and new versions should be compatible as well (as long as it isan’t too outdated). Let’s get started!

Matlab GUI Tutorial - Basic Data Processing Tool
26 Nov 2007 Quan Quach 45 comments 18,094 views

Visual Portion of the GUI
1. First, download the GUI here. Unzip the files and place them wherever you please. Note, that only the visual part of the GUI is completed. All of the code still needs to be added before the GUI will function. 2. Now, type guide at the command prompt.

3. Choose to open the GUI by clicking on “Open Existing GUI”. Click on “Browse” to locate where you saved the GUI files.

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

5. Click on the

icon on the GUI figure to bring up the accompanying .m file.

6. The m-file is bare and contains no code for each of the callbacks. The code will be added and explained in the subsequent sections.

Matlab GUI Tutorial - Basic Data Processing Tool
26 Nov 2007 Quan Quach 45 comments 18,094 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. 1. Add the following code under the addFiles_pushbutton_Callback:
2. %gets input file(s) from user. the sample data files have extension .s2p 3. [input_file,pathname] = uigetfile( ... 4. {'*.s2p', 'Data Files (*.s2p)'; ... 5. '*.*', 'All Files (*.*)'}, ... 6. 'Select files', ... 7. 'MultiSelect', 'on'); 8. 9. %if file selection is cancelled, pathname should be zero 10. %and nothing should happen 11. if pathname == 0 12. return 13. end 14. 15. %gets the current data file names inside the listbox 16. inputFileNames = get(handles.inputFiles_listbox,'String'); 17. 18. %if they only select one file, then the data will not be a cell 19. if iscell(input_file) == 0 20. 21. %add the most recent data file selected to the cell containing 22. %all the data file names 23. inputFileNames{length(inputFileNames)+1} = fullfile(pathname,input_file); 24. 25. %else, data will be in cell format 26. else 27. %stores full file path into inputFileNames 28. for n = 1:length(input_file) 29. inputFileNames{length(inputFileNames)+1} = fullfile(pathname,input_file{n}); 30. end 31. end 32. 33. %updates the gui to display all filenames in the listbox 34. set(handles.inputFiles_listbox,'String',inputFileNames); 35. 36. %make sure first file is always selected so it doesn't go out of range 37. %the GUI will break if this value is out of range 38. set(handles.inputFiles_listbox,'Value',1); 39. 40. % Update handles structure guidata(hObject, handles);

41. 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:
42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. %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 60. if option(end) > length(inputFileNames) 61. set(handles.inputFiles_listbox,'Value',length(inputFileNames)); 62. end 63. 64. % 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);

65. 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.

Matlab GUI Tutorial . %refresh the figure to reflect changes . we want to process the data. the callback will have to parse the input data files. First. This is probably the most complicated callback of this program because of all the subfunctions within it. or they can be placed in their own separate m-file as long as the m-files containing the sub functions are in the same directory as the GUI m-files. %checks to see if the user selected any input files %if not. How is this accomplished? First.'String'). let’s add the code for the start_pushbutton_Callback: 1 2 3 4 5 6 7 8 9 1 0 1 %get the list of input file names from the listbox inputFileNames = get(handles.Basic Data Processing Tool 26 Nov 2007 Quan Quach 45 comments 18. Sub functions can be placed within the GUI m-file itself. Once you’ve added the files that you want to process. nothing happens if isempty(inputFileNames) return end %disables the button while data is processing disableButtons(handles). and then plot the results onto the axes.094 views Processing the Data The next callback we will work with is the start_pushbutton_Callback.inputFiles_listbox.

Basically.plot_p opupmenu. %store filenames so that it will display on the legend handles.'Value')).ignore]=fileparts(inputFileNames{x}). these functions are included so that while Matlab is busy processing the .ext.fileName.legendData(x) = {fileName}. %data is done processing. so re-enable the buttons enableButtons(handles). this variable will be used as a "check" %to see whether the data has been processed or not handles. 1. it might be a good idea to %review this by using the Matlab Help Files handles.processDataCompleted = 1. handles. for x = 1 : length(inputFileNames) %gets the filename without the extension [ignore.data{x} = importMyData(inputFileNames{x}). handles). %the data must be done processing before other Callbacks will be %able to function properly.legendObject = plotData(handles.data.handles.axes1. The first thing you might notice is the disableButtons and enableButtons functions.data = {}. %stores the numerical data using the custom function handles. end handles.1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 refresh(data_processing_tool).get(handles. guidata(hObject.legendData.handles.legendData = {}. %initialize the cell arrays %if you don't know what cell arrays are.

set(handles. and phase. set(handles.plot_popupmenu. set(handles. %this for loop determines where the numerical data starts for p=1:length(data) if (~isempty(str2num(data{p}))) break.'Enable'.'Enable'.'off'). 29. set(handles. 15.'Enable'. magnitude.'Enable'. 27. 17. set(handles. and phase data into a matrix. line = 0. set(handles. 4. 14.'arrow').addFiles_pushbutton.'on').deleteFiles_pushbutton. function [parsedData]= importMyData(name) %this function parses data files that have some header content %and some ending content %the input to this function is the file name of the data file. 13.plot_popupmenu. 28. click here to visit the data parsing post.'on').'off'). function disableButtons(handles) 3. set(handles.export_pushbutton. magnitude.'Enable'.'Pointer'. a = a +1.inputFiles_listbox. 19.'Pointer'. set(handles.'on').'off').'Enable'. The code for the two functions are: 2. set(handles.start_pushbutton. 38. set(handles. %get rid of the last line fclose(fid). 11. end end %this loop saves the numerical data into parsedData %until the numerical data stops . 39. 7. 20. the sample data files being parsed have three columns of data: frequency.'Enable'.'on'). 30.deleteFiles_pushbutton. 21. 6.inputFiles_listbox. 8. 35. The parsing function takes an input file and outputs the frequency. 5. 26. The following is the code for the parsing function. end data(end) = []. 9. To learn more about this feature. For more information on parsing data files. 12.'Enable'.savePlot_pushbutton.savePlot_pushbutton. 23.addFiles_pushbutton. This function is a custom function that parses the input data.'on').'off'). 40. %reads line one by one into a cell a= 1. 18. set(handles.'Enable'. %If the data file is not in the current Matlab directory %you must include the entire directory path.data. function enableButtons(handles) set(handles. click here to visit the post that covers this topic.'off'). %opens the file fid = fopen(name). 36.'off').start_pushbutton. In this tutorial.'Enable'.'Enable'. 22.figure1.'watch'). set(handles. 31. 37. set(handles. 10.'Enable'.'Enable'. 32. 24. 25. 34. The next function you might have questions about is the importMyData function.export_pushbutton. while line ~= -1 line = fgetl(fid). set(handles.'on').'off').'off'). 33. the user cannot click on any of the other buttons.'Enable'. set(handles. set(handles.'on').reset_pushbutton. set(handles. 16.reset_pushbutton.figure1.'on').'Enable'.'Enable'. data{a} = line.

1). Writing a separate custom function for plotting the data can be extremely useful because you can call it later on in any of the callbacks if you need to. You can tell that it is a cell by the curly brackets used. 58.'Best'). 74.41. 60. 77. this plot function is catered to the sample data files that I created. 70. %clear the axes axes(axesName). you will probably have to play around with the parsing function to get it to parse your data correctly. end %add a legend to the plot legendObject = legend(legendData.:) = temp. Finally. function [legendObject]=plotData(data. 75. so if you don’t know how to use them. 52. parsedData(x-p+1.'Location'. 67. you should consult the Matlab help!! 45. This function returns the legend object of the plot so that it can be used later in other parts of this GUI. and the type of plot.axesName. 59. Once again. 54. for x=p:length(data) 42. the legend data. 61. 46.'Best'). end 43.2)).'none').3)). The function takes in 4 arguments. title('Insert Title Here') xlabel('Frequency (GHz)') ylabel('Magnitude (dB)'). %set the axes to plot hold on grid on %plot the magnitude plot if (option==1) for x=1:(length(data)) plot(data{x}(:.data{x}(:.1). 72.option) cla(axesName). 53. end %add a legend to the plot legendObject= legend(legendData. end Note that if you plan to parse your own data which uses a different data file format. 62. 51. The data that will be plotted. Also. 66. Cell arrays can be very versatile. the axes that the data will be plotted on (this argument is helpful if you have more than 1 axes on your GUI). 73. 56. and not a matrix. 48. You will probably have to make some minor mods to it if you plan to use it to process other types of data files. 44. title('Insert Title Here') xlabel('Frequency (GHz)') ylabel('Phase (Degrees)'). 71. 50. 69. 76. 65.'Location'. notice how the data returned from importMyData is stored into a cell. temp = str2num(data{x}). 47. 63.legendData. the last custom function within this callback is the plotData function. end hold off %allow legend titles to be displayed properly set(legendObject.'Interpreter'. 49. 68. {}. if(isempty(str2num(data{x}))) break. %else plot the phase plot else for x=1:(length(data)) plot(data{x}(:.data{x}(:. 57. 55. 64. .

For more information on this.data. . 20. The pop-up menu is relatively easy to use and allows the user to select between displaying the magnitude plot or the phase plot on the axes. The handles. end 7. plotType = get(hObject.processDataCompleted == 0) 5. 16. if (handles. 3. 23. if magnitude option is chosen 10.handles.'Value').handles. 18. %nothing happens when this button is pressed if (handles. %nothing happens when this button is pressed 4. refresh(data_processing_tool).legendObject = plotData(handles. savePlotWithinGUI(handles.plotType). %if the data hasn't been processed yet. guidata(hObject.094 views Pop-up Menu and Save Plot Callbacks 1. %plotType = 2. 17.legendObject to use. 22. 8. return 6. Add the following code to plot_popupmenu_Callback 2. if you remember. %plotType = 1. In this callback. %if the data hasn't been processed yet.legendData. handles).legendObject). Run the GUI. add the input files. %plots the data 14. The next callback is the savePlot_pushbutton_Callback. we put the handles. 19.axes1. %get the value of the current Pop-up menu selection 9.After adding in all of this code.handles. 15.processDataCompleted == 0) return end disableButtons(handles). 21. it would be a good idea to test out the GUI. handles. if phase option is chosen 11. is an output from the plotData function.axes1. 13. you can read this post here. 24. 12. and process the data.legendObject. Click here if you need a refresher on how Pop-up Menus work.Basic Data Processing Tool 26 Nov 2007 Quan Quach 45 comments 18. You should get something that looks like this (click on figure to enlarge): Matlab GUI Tutorial .

'Units'). %saves the plot saveas(newFig. %copies axesObject onto new figure axesObject2 = copyobj(axesObject. enableButtons(handles). %if user cancels save command.newFig).'Bitmap (*. legendObject) %this function takes in two arguments %axesObject is the axes object that will be saved (required input) %legendObject is the legend object that will be saved (optional input) %stores savepath for the phase plot [filename. 'Save picture as'.0) || isequal(pathname.fig'.'Units'. function savePlotWithinGUI(axesObject.fullfile(pathname.[15 5 axes_pos(3) axes_pos(4)]).'Units'. %realign the legend object on the new figure set(legendObject2.'Units'.0) return end %create a new figure newFig = figure.'Enhanced Meta File (*. nothing happens if isequal(filename.'Position'. .[15-axes_pos(1)+legend_pos(1) 5axes_pos(2)+legend_pos(2) legend_pos(3) legend_pos(4)] ). pathname] = uiputfile({ '*. set(legendObject2. %get the units and position of the axes object axes_units = get(axesObject.axes_units).'Position'. legend_pos = get(legendObject.newFig). set(axesObject2. ..[15 5 axes_pos(3)+30 axes_pos(4)+10]). %copies the legend onto the the new figure legendObject2 = copyobj(legendObject.'Figure (*. guidata(hObject. set(newFig.axes_units).'default'). '*.bmp'. axes_pos = get(axesObject.. '*.fig)'}.emf)'.'Units').25. handles).'Position'). filename)) %closes the figure close(newFig) . ... end %adjusts the new figure accordingly set(newFig.'Position').'Position'.bmp)'.emf'..legend_units). %realign the axes object on the new figure set(axesObject2. %if a legendObject was passed to this function . if (exist('legendObject')) %get the units and position of the legend object legend_units = get(legendObject.

1)]. pathname] = uiputfile({'*.legendData).handles.xls'. %it is assumed that the frequency range is the same for all the data sets magnitudeData = [data{1}(:. magDB{x} = 'Mag (dB)'. %nothing happens when this button is pressed if (handles. phaseDegrees{x} = 'Phase(Degrees)'.Now.2)]. fileNames) %stores savepath for the phase plot [filename. phaseData = [data{1}(:.data. or add it to the data-processing-tool. This is what you should get (click on figure to enlarge): Matlab GUI Tutorial .xls)'}.'Save Data to Excel File'. phaseData = [phaseData data{x}(:. end saveFileName = fullfile(pathname.2)]. Since many people work with Excel.processDataCompleted == 0) return end saveDataToExcel(handles. Lets see how we can export data to Excel.1)]. .m file. Specifically.'default').'Magnitude Data'. run the GUI to check that the pop-up menu and save plot functionality work.Basic Data Processing Tool 26 Nov 2007 Quan Quach 45 comments 18. Add this code as its own separate m-file. filename).'Excel (*. adding a feature to export data to Excel can come in quite handy. lets try to select the “Phase” option on the pop-up menu. function saveDataToExcel(data. Add the following code to export_pushbutton_Callback: %if the data hasn't been processed yet.'A1'). xlswrite(saveFileName.094 views Exporting the Data to Excel Exporting data to a medium that users can manipulate is very desirable.['Data File' fileNames]. for x = 1:length(fileNames) magnitudeData = [magnitudeData data{x}(:.

Application'). excelObj. we move on to the next one %by incrementing the count variable if (temp == worksheets.Delete.Quit. %if there's only one sheet left. we can use the following function that is discussed in this post. The function that is used in this example does the latter.'A2'). and to test the exporting capabilties.workbooks.'Phase Data'.'A1'). fileName = 'C:\Documents and Settings\matlab\myExcelFile.'Phase Data'.'A3'). delete(excelObj). count=1. xlswrite(saveFileName. xlswrite(saveFileName.Close(false). if (temp == 1) break.'A3').['Frequency (GHz)' phaseDegrees].count) count = count + 1.['Data file: ' fileNames]. you can export a separate Excel file for each input file.'A2').['Frequency (GHz)' magDB]. xlswrite(saveFileName. Matlab GUI Tutorial . end %this command will only delete the sheet if it is empty worksheets. %opens up an excel object excelWorkbook = excelObj.Save. for x=1:numSheets %stores the current number of sheets in the workbook %this number will change if sheets are deleted temp = worksheets. and lump all the phase data into another file.'Magnitude Data'.Open(fileName).Basic Data Processing Tool . excelWorkbook. Once again.'Phase Data'. we must leave it or else %there will be an error.xlswrite(saveFileName. xlswrite(saveFileName. worksheets = excelObj.phaseData. end end excelWorkbook.Count. function deleteEmptyExcelSheets(fileName) %this function erases any empty sheets in an excel document %the input fileName is the entire path of the file %for example.Item(count). deleteEmptyExcelSheets(saveFileName). There are many different ways you can export your data to excel. or you can lump all the magnitude data together into one file.'Magnitude Data'. For instance.sheets. %if a sheet was not deleted. %total number of sheets in workbook numSheets = worksheets.phaseData. And to erase those empty sheets when the Excel file is created.xls' excelObj = actxserver('Excel.count. you should try testing the GUI to make sure it works.

varargin) 4.'CloseRequestFcn'.'Yes'). 'Yes'. eventdata. 1. In addition.'toolbar'.. %resets the GUI by clearing all relevant fields . %enables toolbar 7. for the reset button.'figure'). 5. handles. Instead of closing and opening the GUI to get to the starting state.output = hObject. handles) 18. 17. function data_processing_tool_OpeningFcn(hObject. 6. Now. 8. %the variable is set to 1 once the data has been processed 10.processDataCompleted = 0. For more information on the “Close GUI Confirmation”. set(hObject. this section will also introduce a “Reset Button” to the GUI. and Reset Button There are a couple other modifications that must be done to the opening function. 2. 14. 15.. we are going to add the standard tool bar and the “close GUI confirmation dialog”. handles. % Update handles structure guidata(hObject. case 'Yes'.. function closeGUI selection = questdlg('Do you want to close the GUI?'.094 views Opening Function. lets deal with the opening function. Close GUI Confirmation.. %this command asks the user to confirm closing of GUI 13. 12. handles). handles. First. you can visit this post.'No'.26 Nov 2007 Quan Quach 45 comments 18. %this variable used to prevent users from breaking the GUI 9. % 11. Here. switch selection.figure1. eventdata. %% 3. the user can simply click on the “reset” button.'closeGUI'). 'Close Request Function'.. function reset_pushbutton_Callback(hObject. set(handles.. Resetting your GUI to the default state can save the user a lot of time and fustration. delete(gcf) case 'No' return end 16.

To protect against this. 23. 28.axes1.'Value'. 30. %clears the contents of the listbox set(handles.0).figure1.Close GUI Confirmation 23 Nov 2007 Quan Quach 15 comments 6. Both earlier versions and new versions should be compatible as well (as long as it isan’t too outdated). Matlab version 2007a is used in writing this tutorial. If you’re new to creating GUIs in Matlab.399 views Introduction This tutorial will show you how to create a confirmation window when you attempt to close the GUI. handles). Matlab GUI Tutorial . we can implement a confirmation window that appears when the user attempts to close the GUI.plot_popupmenu. 20. %clears the axes cla(handles. set(handles. the user might accidentally close the GUI window without meaning to. 24. you need to add the following line of code to the opening function of your GUI. 26.@closeGUI). 31. Sometimes. %updates the handles structure guidata(hObject. 22. set(handles. 21.''). . Let’s get started! Creating the Confirmation Window: Method 1 1. 25.'reset'). This is the end of the tutorial.processDataCompleted = 0. 29. This feature can protect the user from losing any work that has been performed.'CloseRequestFcn'.1). you should visit this tutorial first. %set the popupmenu to default value set(handles.'String'.'Value'.inputFiles_listbox. Basic knowledge of Matlab is highly recommended. 27. handles. This tutorial is written for those with some experience creating a Matlab GUI.inputFiles_listbox. First. 32.19.

10..m file. we use the single quotation marks. return end Creating the Confirmation Window: Method 2 1. 'Close Request Function'. switch selection. 'Yes'.. %evnt is the The event data structure (can be empty for some callbacks) 6. Notice that we did not define any input arguments here. 7. go ahead to the next page. Next. function closeGUI 4. 2. Matlab GUI Tutorial . but make sure it’s saved in the same directory where the GUI files are located.figure1. 11. you need to add the following line of code to the opening function of your GUI.. you are assigning a separate m-file to the close request function of the figure. function closeGUI(src.'CloseRequestFcn'. 9. 5. If you want to see an example. First. 6.evnt) 4. 'Close Request Function'. case 'No' 13..'Yes').'Yes'). 10.. 8. Next. switch selection. 8.. selection = questdlg('Do you want to close the GUI?'. case 'No' 12. 'Yes'. 9. By using the single quotation marks.. 3. copy this code into a separate .'No'.m file. case 'Yes'. Make sure to put this line of code before the line guidata(hObject. delete(gcf) 12. selection = questdlg('Do you want to close the GUI?'. copy this code at the end of the GUI .'No'.. 7.. handles). case 'Yes'. 3.This line is of code is telling matlab to run the closeGUI function once someone attempts to close the GUI figure.Close GUI Confirmation . delete(gcf) 11. return end And that’s it!!! Pretty simple like I mentioned.. Make sure to put this line of code before the line guidata(hObject. but make sure it’s saved in the same directory where the GUI files are located.m file OR in a separate . %src is the handle of the object generating the callback (the source of the event) 5. handles). set(handles..'closeGUI'). Notice that instead of the @.. 2.

download the sample GUI here. First. type guide at the command prompt. 3. Click on “Browse” to locate where you saved the GUI files. 2. Now. 4. Here is what the GUI should look like when you open it: .399 views Example of the Confirmation Window in Effect 1.23 Nov 2007 Quan Quach 15 comments 6. Choose to open the sample GUI by clicking on “Open Existing GUI”. Unzip the files and place them wherever you please.

Now.. %this function is called when the user attempts to close the GUI window 10..@closeGUI). Now. Add the following code to the opening function. You should see the following GUI appear .'No'. %nothing happens 18.m file.'Yes'). 8. 19. 6. case 'Yes'. %this command brings up the close window dialog 12. return end 23...figure1. Make sure to add the above line of code before this line of code: guidata(hObject.. save your . the GUI window is closed. %if user clicks yes. selection = questdlg('Do you want to close the GUI?'. add the following code to the end of the GUI m-file.5. switch selection. delete(gcf) 21.. 15. function closeGUI(src. Click on the icon on the GUI figure to bring up the accompanying . 11. 7. 20.evnt) 9. 14. handles).m file and run the GUI. 16.'CloseRequestFcn'. closeGUI_tutorial_OpeningFcn set(handles. 'Yes'. otherwise 17. 13. case 'No' 22. 'Close Request Function'.

you are now able to add tables to a GUI. looks great! . displaying your data in tabular form is easy. In the past. Click “yes” to close the GUI.282 views With the release of MATLAB 2008b. You should see the following appear: 25. How to Display Data 27 May 2009 Quan Quach 12 comments 7. there was no easy way to display your data in tabular form. With the UITABLE component. try to close the GUI.UITABLE Part 1. MATLAB GUI Tutorial . Now. and most importantly. This is the end of the tutorial.24. or click “no” to keep it open.

Contents       Adding a Table to Your GUI using GUIDE Displaying Data on the Table Adding Column and Row Labels Modifying your Table through the m-file Next Time Links and Downloads Adding a Table to Your GUI using GUIDE Within the GUIDE framework. Here’s what the GUI will look like within GUIDE: . you can add a table to your GUI using the following icon from the toolbar: .

uitable1. create a data matrix that has 5 columns. we use the following code: % --.myData ). Thus. Now.'data'. handles) % hObject handle to populate_pushbutton (see GCBO) % eventdata reserved . %now populate the table with the above values set(handles.4). In the populate_pushbutton callback. 4 rows myData = rand(5. let’s run the GUI and push the button! . we’re going to need to add some code to the pushbutton’s callback.to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %first.Displaying Data on the Table We are going to populate the UITABLE component with data by pushing the “Populate Table” button. eventdata. function populate_pushbutton_Callback(hObject.Executes on button press in populate_pushbutton.

A neat feature is that the table is smart enough to fill out the table according to the size of the data matrix that you feed it. as shown below. Within the GUIDE framework.100). The table would incorporate the use of scroll bars. This helps differentiate your data and makes it easy to identify. . we can modify the labels by first bringing up the Property Inspector for the UITABLE. Adding Column and Row Labels A good way to spruce up your table is to add row and column labels. So if I had done the following instead: myData = rand(100. This can be done by double clicking the UITABLE component.

if you click on any of the fields in the above picture.Now. This is where you can add Row and Column labels. For example: . it will bring up the Table Property Editor.

you just need to modify the names. Similarly. you can do the same for the columns. Finally. and that you select the “Show names entered below as the row headers” option. you should see the following: .Make sure you click on the “Rows”. Once you’re done with that.

A well labeled table that displays your data beautifully! Modifying your Table through the m-file Sometimes it’s easier to work from within the m-file framework. you can see the final result. We could have done exactly what we did above programmatically through the mfile.And once you run your GUI. rather than the GUIDE framework. In the opening function we could have done the following: .

and much more.rowHeaders).columnHeaders).uitable1. say you wanted to take the contents of the table manipulate the data. For example.'Dagger'.'MATLAB'. %do the same for the column headers columnHeaders = {'Quan'.'Zane'}.404 views Last time.'Rob'.'RowName'.fig file every time you want to make a change. And if you are going to apply dynamic labeling.'!!!!!!'}.'ColumnName'. Contents   Accessing Table Data within GUI Callbacks Accessing only the Selected Data . If you don’t know the size of your table beforehand. we’re going to learn how to work with table data within a GUI framework. In this example.%store the row headers into a cell array rowHeaders = {'Blink'.uitable1. set(handles. we assumed that we knew the dimensions of our table. This time. we learned how to display data onto a table. How To Access Table Data 31 May 2009 Quan Quach 19 comments 7. then it can be difficult to apply data labels that are meaningful. %set the row labels set(handles. This tutorial will explain how to do that.'Daniel'.UITABLE Part 2. MATLAB GUI Tutorial . then working from the m-file is going to be much easier. you obtain more flexibility since you won’t have to go back and modify the . By working through the m-file.'Loves'.

when I press the “Add 3″ button.'data'). Let’s take a look at the callback for the add button: function add_pushbutton_Callback(hObject. handles) % hObject handle to add_pushbutton (see GCBO) % eventdata reserved . %update the table set(handles. So now.tableData).uitable1. eventdata.  Next Time Links and Downloads Accessing Table Data within GUI Callbacks Let’s say you have the following GUI: For simplicity sake.'data'. . %add 3 to the table tableData = tableData + 3. let’s assume that you would like to create a button that will add 3 to each of the entries of the table when the button is pressed.to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %get the table data tableData = get(handles. it adds 3 to the table! This is just a simple example to show how to extract the data from the UITABLE.uitable1. and to perform an operation on it. How would you go about doing this? It’s actually quite straightforward.

and then clicking the following icon as shown in the image below. Let’s say you selected a couple of cells that you want to sum. How would you go about doing this? Read on and all will be revealed.Accessing only the Selected Data Now. Enabling CellSelectionCallback The first thing we need to do is to enable the Cell Selection Callback. let’s up the difficulty level a bit. But first. You can do this by bringing up the Property Inspector for the UITABLE. why are we doing this? Enabling this callback will allow us to keep track of what cells are being selected on the table. . as shown in the image below (You can hold onto the CTRL button while clicking on individual cells to select multiple cells).

Executes when selected cell(s) is changed in uitable1. your m-file should have been updated to include the following: % --. the CellSelectionCallback field should now be populated as shown in the image below: . eventdata.If you did it correctly. handles) % hObject handle to uitable1 (see GCBO) % eventdata structure with the following fields (see UITABLE) % Indices: row and column indices of the cell(s) currently selecteds % handles structure with handles and user data (see GUIDATA) In addition. function uitable1_CellSelectionCallback(hObject.

let’s create and initialize a variable to hold the table cell selection information. . and initialize it in the opening function. % hObject handle to figure % eventdata reserved . handles) % hObject handle to uitable1 (see GCBO) % eventdata structure with the following fields (see UITABLE) % Indices: row and column indices of the cell(s) currently selecteds % handles structure with handles and user data (see GUIDATA) %every time the cell selection changes. We will call this handles. handles.Adding the Necessary Code First.selectedCells.Executes just before uitable_tutorial_02 is made visible. see OutputFcn.Executes when selected cell(s) is changed in uitable1. function uitable1_CellSelectionCallback(hObject. we update this data %eventdata stores the indices of the selected cells handles.selectedCells = eventdata. Next.Indices. we go to the uitable1_CellSelectionCallback. which is the callback that we just enabled.to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to uitable_tutorial_02 (see VARARGIN) %initialize this variable handles.selectedCells = []. function uitable_tutorial_02_OpeningFcn(hObject. eventdata. % --. % --. varargin) % This function has no output args. eventdata.

columns] = size(handles.'data').uitable1. %loop through each selected cell and keep a running sum . eventdata. handles) % hObject handle to sumNumbers_pushbutton (see GCBO) % eventdata reserved . handles). function sumNumbers_pushbutton_Callback(hObject. we need to write the callback for the button we just added: % --. The modified GUI looks like this: Now.Executes on button press in sumNumbers_pushbutton. we’re going to add another button and a static text component to display the sum.%update the gui data guidata(hObject. %get the data from the UITABLE tableData = get(handles. Adding the Selected Numbers Together First.selectedCells). %initialize the sum sum = 0.to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %get the number of rows and columns [rows.

tableIndices(x.num2str(sum)) And there you have it. so stay tuned! Contents   Zane’s GUI Adding in Panels .%can anyone thing of a better way to do this? for x=1:rows sum = sum +tableData(tableIndices(x. we are planning on opening up this series to include GUIs from our reader base. In the future. end %display the sum on the GUI set(handles.sum_text. Zane Montgomery! This will be an ongoing project so don’t think the final result at the end of this post is the end. In this series.2)). a series that will provide our readers with tips and tricks on how they can make their GUIs beautiful on both the inside and outside. and then sum up the value of the contents! Next Time Pimp My GUI 13 Jan 2009 Quan Quach 12 comments 3. now you can select any number of cells.118 views The idea for Pimp my GUI is taken from the popular MTV show Pimp My Ride. we start with a freshly created GUI from our newest prodigy.'String'.1). Blinkdagger proudly presents Pimp My Gui.

Issaquah. I have to work at one of three offices during the week (Federal Way. I had recently completed some of the blinkdagger tutorials and thought a GUI would be a great project to practice my new skills. why not have it all completed for me! . I could have just made a simple Excel sheet. I heard that gas for work could be deducted from taxes so I decided to keep track of all of my miles. Lynnwood). One of my worries working for this company was the price of gas because driving would take up a good part of my pay. but then I would have to eventually come back and add everything up manually.   Labeling Panels Reorganization Final Thoughts Zane’s Commuter GUI About Zane’s GUI: As a tutor.

Adding in Panels The panel icon on the GUIDE editor looks like this: You can find it here: . .

Panels are an effective way to group together common elements and are simple to use. the panels immediately give the GUI a better structure and organization. They provide lines and boundaries and makes it easier for the end user to navigate the GUI easily.As can be seen. Labeling Panels .

This helps clean up the GUI even more and removes extraneous information. we removed the redundant headers.In this part of the revamping. In addition. the panel sizes are reduced to a size that adequately frames the content as to not waste space. Also. we have simply given the panels a title name to identify that particular panel. Reorganization .

we talked about using a custom menu bar to retain functionality while clearing up space on a GUI. In this post. the “Input Data” panel was extended to include the rest of the buttons so that there wouldn’t be any elements that are orphaned and just dangling alone. Join us next time as we continue to transform Zane’s GUI from the ugly duckling to the beautiful swan. In addition. there is extra space that is no longer needed. Pimp My Gui Part 3: Help Me Help Yourself 10 Feb 2009 Quan Quach 2 comments 2. This reduces the GUI size yet again and makes it more compact. In the previous post.316 views Blinkdagger proudly presents Pimp My Gui. a series that will provide our readers with tips and tricks on how they can make their GUIs beautiful on both the inside and outside.After some reorganization of the GUI. Final Thoughts Panels are an effective way to separate your GUI into manageable sections. giving the GUI definition. we’re going to .

but we never did anything for the “help” portion of the GUI: Contents    How to use this GUI: Quick User Guide About this GUI Putting it all Together . The help feature should be informative and simple so that any person can learn how to use the GUI quickly.discuss how to implement a “help” feature for your GUI. author. The help feature should offer other useful information such as the version number. we ended up with this GUI. and other tidbits of information. In the last post.

  Addpath Next Time How to use this GUI: Quick User Guide A simple but effective way to implement a help screen is to create another standalone GUI. I populated the text field with some helpful information regarding the GUI and detailed a succinct user’s guide. I created a standalone GUI that consists of only a static text component. When the GUI is called by the user. For example. the user will see the following: .

If you can’t fit all the information into one screen. name of author. . date of creation. you can add more tidbits and information depending on the actual GUI. You might also want to add a FAQ section here if you feel your GUI needs some extra explanation. This part should inform the user about what version of MATLAB the GUI was designed on.Of course. About this GUI I also created a stand alone GUI for the “About”. some contact information. you can also utilize pushbuttons that will change the static text when the button is pressed. and the version number of the GUI.

the user will see the following: .When the GUI is called by the user.

Putting it all together All we have to do now is to call the appropriate help GUI in the appropriate callback. MATLAB automatically created callbacks for each menu item. eventdata. When the menu items for the help menu was created. handles) %this is the name of the help GUI that contains the help information helpGUI_description the callback for the “About this GUI” menu item is . pretty straightforward stuff. the callback for the “How to use this GUI” menu item is: function helpGUI_Callback(hObject.

so its usually a good idea to put all your sub functions and sub GUIs in a lower level folder. the following image shows how I originally had my m-files organized. eventdata. it can be advantageous to store them in appropriate subdirectories. For example. It can get a little crowded in the main directory of your GUI. you can store them in a separate directory and simply add the path of that directory. .function aboutGui_Callback(hObject. handles) %this command calls the GUI that has the "about" information aboutGUI_description Addpath I have found that the addpath command within MATLAB can really help you keep your files organized. The main GUI files are Tutor_Commuter_QQ_05.m. The rest of the files are used in creating the help.fig and Tutor_Commuter_QQ_05. If your GUI utilizes other m-files or images.

which in this case will be where %the main GUI is located addpath(fullfile(pwd. all that has to done is to add the path of the subfunctions within the Opening Function of the main GUI. we’ll open up the floor and ask for GUIs from our readers! Until next time .'subfunctions'). %the addpath adds the subfunctions folder onto the MATLAB path. Now. In the near future. All the files except the main files are placed in the subfunctions folder.In the following image. you can see how I reorganized the files. . Next Time It looks like we’ve revamped Zane’s GUI so that it’s obtained a shade of respectability. . . If you guys have any more ideas on what can be done. we’d love to hear about it. m-files %within this directory will be run as if it were in the same directory as the %main GUI itself %the fullfile command combines directory names and parts %pwd is the "present working directory".

90.14790 -4:998& 203:9028 ..94305&*.9.557457.9 0..7/89:11 0390203:90281479005203:. .940907 0.9.70..20419005&9.90/ % .-...9005&390..9147.039/..90/..-.203:902   90..3/08   988903. !:9939.90...943 05&*/08.557457.75943 90.81470. 57099 897.-.70.:942.38900531472.-.-.  -0..9...8.094/434894.14790 494:8098& 203:9028 1:3.439.

9 0.014/07  470.08484473..3/70.-4:9&*/08..805.-4:9:*.422.990.3/.04:89489470902 3..3&108.422.990.//5.4070.947 9.39.70:80/3.//905.943 .9/70.9.943..75943 //5.039/.-.250 9014432.74/0/3902.90/70.4:7 8:-1:3.3/93%.-4:931472.370.9 .3894709023.890./..70%:947*422:907*""*  1.7.3/825.3/8:-&83.947414:7& 8498:8:..9438.3/%:947*422:907*""*  2 %0708941 90108.30/ 14:7&:90849072 108472.309 .30/ %0 2.890&9.945:9.  -0.939005   .9419.557457.94708  4:./22 10847.3/08   98.947.908:-/70.3-0.9..08 9.44//0.9..70..1:3.. .054:0054:7108 47.014:3/9.

3/5..941908:-1:3.8 90 2.9 1:10 5/ 8:-1:3.30/.705.943814/07   4 .30/90108 901080.9438  09%20 944800 ..//8908:-1:3.250/.8147&817424:770.0940.7 1:9:70 0 4503:5901447.947 .3&  90.9.94341902.//5.0/3908:-1:3.843.39014432.7.070..9.99 84-9.3-0/430 0 /4.380047047.0.947..8190703908.3/.32470/0.//905.30 8&849.9 2 108 9398/70.943814/07439490%5.9.20/70../04170850.9473.422.42-308/70.-9 1 4::8.947-07:3.894/430894.3 108.398.3/.//5.9.3&84.059902.80-0070 902./078&39309920     ...9.8.94389390 5033 :3.208.90/ .798  5/8905708039473/70.-4:99 39030.0 4:.3&9801  901:10.

Sign up to vote on this title
UsefulNot useful