MATLAB Programming/Advanced Topics/Toolboxes and Extensions/GUIDE

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The GUIDE Toolbox provided by MATLAB allows advanced MATLAB programmers to provide Graphical User Interfaces to their programs. GUIs are useful because they remove end users from the command line interface of MATLAB and provide an easy way to share code across nonprogrammers. In addition by using special compilers the mathematical ability of MATLAB seamlessly blends in with the GUI functionality provided. Just to provide an example, assume you are writing a nonlinear fitting system based on the levenburg marquardt algorithm. Implementing a same GUI in VC++ would take at least a month of effort. But in MATLAB with the existing nlinfit function the time for such an endeavor would be hours instead of days.

The figure shows an example of a simple GUI created with the GUIDE toolbox, it takes as input two numbers adds them and displays them in the third textbox, very simple but it helps illustrate the fact that such a GUI was created in minutes. The first section we need to understand is the concept of a callback

CallBack[edit | edit source]

A callback is a functions executed whenever the user initiates an action by clicking for example on a button or pressing a key on the keyboard. Programming a callback is therefore the most important part of writing a GUI. For example in the GUI illustrated above, we would need to program a callback for the button Add. This is provided as a callback in the code. The code is provided below and illustrates how to write a simple callback.

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
n1 = get(handles.edit2,'string');
n2 = get(handles.edit1,'string');
S = str2double(n1) + str2double(n2);

In this piece of code I get the numbers as strings from the edit boxes and then convert them into numbers using the str2double function provided in MATLAB. I then set the string for the other edit box as the sum of these two numbers. This completes the simple example of a GUI needed to add two numbers. To illustrate a more complex example I show how a simple exponential function can be plotted and you can change the function's parameters. With a little bit of imagination you could make it plot any arbitrary function you enter. To make the example even more complex I have two GUIs, one is the control GUI and the other is the plotting GUI, this allows the user to program some of the more complicated functionality expected out of the modern GUI systems.