Matlab GUI Tutorial - Basic Data Processing Tool
26 Nov 2007 Quan Quach 23 comments 24903 views
Processing the Data
The next callback we will work with is the start_pushbutton_Callback. This is probably the most complicated callback of this program because of all the subfunctions within it. Sub functions can be placed within the GUI m-file itself, 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. Once you’ve added the files that you want to process, we want to process the data. First, the callback will have to parse the input data files, and then plot the results onto the axes. How is this accomplished?
First, let’s add the code for the start_pushbutton_Callback:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | %get the list of input file names from the listbox inputFileNames = get(handles.inputFiles_listbox,'String'); %checks to see if the user selected any input files %if not, nothing happens if isempty(inputFileNames) return end %disables the button while data is processing disableButtons(handles); %refresh the figure to reflect changes refresh(data_processing_tool); %initialize the cell arrays %if you don't know what cell arrays are, it might be a good idea to %review this by using the Matlab Help Files handles.data = {}; handles.legendData = {}; for x = 1 : length(inputFileNames) %gets the filename without the extension [ignore,fileName,ext,ignore]=fileparts(inputFileNames{x}); %store filenames so that it will display on the legend handles.legendData(x) = {fileName}; %stores the numerical data using the custom function handles.data{x} = importMyData(inputFileNames{x}); end handles.legendObject = plotData(handles.data,handles.legendData,handles.axes1,get(handles.plot_popupmenu,'Value')); %the data must be done processing before other Callbacks will be %able to function properly. this variable will be used as a "check" %to see whether the data has been processed or not handles.processDataCompleted = 1; %data is done processing, so re-enable the buttons enableButtons(handles); guidata(hObject, handles); |
-
The first thing you might notice is the disableButtons and enableButtons functions. Basically, these functions are included so that while Matlab is busy processing the data, the user cannot click on any of the other buttons. To learn more about this feature, click here to visit the post that covers this topic. The code for the two functions are:
function disableButtons(handles) set(handles.figure1,'Pointer','watch'); set(handles.start_pushbutton,'Enable','off'); set(handles.reset_pushbutton,'Enable','off'); set(handles.addFiles_pushbutton,'Enable','off'); set(handles.savePlot_pushbutton,'Enable','off'); set(handles.deleteFiles_pushbutton,'Enable','off'); set(handles.inputFiles_listbox,'Enable','off'); set(handles.plot_popupmenu,'Enable','off'); set(handles.export_pushbutton,'Enable','off');
function enableButtons(handles) set(handles.figure1,'Pointer','arrow'); set(handles.start_pushbutton,'Enable','on'); set(handles.reset_pushbutton,'Enable','on'); set(handles.addFiles_pushbutton,'Enable','on'); set(handles.savePlot_pushbutton,'Enable','on'); set(handles.deleteFiles_pushbutton,'Enable','on'); set(handles.inputFiles_listbox,'Enable','on'); set(handles.plot_popupmenu,'Enable','on'); set(handles.export_pushbutton,'Enable','on');
-
The next function you might have questions about is the importMyData function. This function is a custom function that parses the input data. For more information on parsing data files, click here to visit the data parsing post. In this tutorial, the sample data files being parsed have three columns of data: frequency, magnitude, and phase. The parsing function takes an input file and outputs the frequency, magnitude, and phase data into a matrix. The following is the code for the parsing function.
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. %If the data file is not in the current Matlab directory %you must include the entire directory path. %opens the file fid = fopen(name); %reads line one by one into a cell a= 1; line = 0; while line ~= -1 line = fgetl(fid); data{a} = line; a = a +1; end data(end) = []; %get rid of the last line fclose(fid); %this for loop determines where the numerical data starts for p=1:length(data) if (~isempty(str2num(data{p}))) break; end end %this loop saves the numerical data into parsedData %until the numerical data stops for x=p:length(data) if(isempty(str2num(data{x}))) break; end temp = str2num(data{x}); parsedData(x-p+1,:) = temp; end
Note that if you plan to parse your own data which uses a different data file format, you will probably have to play around with the parsing function to get it to parse your data correctly. Also, notice how the data returned from importMyData is stored into a cell, and not a matrix. You can tell that it is a cell by the curly brackets used, {}. Cell arrays can be very versatile, so if you don’t know how to use them, you should consult the Matlab help!!
-
Finally, the last custom function within this callback is the plotData function. 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. This function returns the legend object of the plot so that it can be used later in other parts of this GUI. The function takes in 4 arguments. The data that will be plotted, the legend data, the axes that the data will be plotted on (this argument is helpful if you have more than 1 axes on your GUI), and the type of plot.
function [legendObject]=plotData(data,legendData,axesName,option) cla(axesName); %clear the axes axes(axesName); %set the axes to plot hold on grid on %plot the magnitude plot if (option==1) for x=1:(length(data)) plot(data{x}(:,1),data{x}(:,2)); end %add a legend to the plot legendObject = legend(legendData,'Location','Best'); title('Insert Title Here') xlabel('Frequency (GHz)') ylabel('Magnitude (dB)'); %else plot the phase plot else for x=1:(length(data)) plot(data{x}(:,1),data{x}(:,3)); end %add a legend to the plot legendObject= legend(legendData,'Location','Best'); title('Insert Title Here') xlabel('Frequency (GHz)') ylabel('Phase (Degrees)'); end hold off %allow legend titles to be displayed properly set(legendObject,'Interpreter','none');
Once again, this plot function is catered to the sample data files that I created. You will probably have to make some minor mods to it if you plan to use it to process other types of data files.
After adding in all of this code, it would be a good idea to test out the GUI. Run the GUI, add the input files, and process the data. You should get something that looks like this (click on figure to enlarge):
23 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’??