MATLAB GUI TUTORIALby Dr. S.S.Limaye

Why use GUI(Graphical user interface)?

GUI makes your program very user friendly. It has many useful elements like edit boxes, sliders, push buttons, graph axes etc. Using these elements, you can make a professional program like VC++ or VB. This is especially useful to electronics engineers as they are not generally familiar with windows based programming languages.

Assignment 1

In this simple assignment, we will make an adder, that adds the contents of two edit boxes and displays the result in a third one, on pushing a button.

Solution

Start MATLAB. Start GUI IDE by typing “guide” at the command prompt. “Create new GUI” tab is selected and “Blank GUI(Default)” option is also selected. Simply press OK. The GUI design editor appears with title “untitled.fig”. You can give it any desired title while saving. We want to finally achieve the following result.

There is a palette of various tool buttons on the left side. By default, the tool names are not displayed to save space. But as a beginner, it may be a good idea to choose the option of displaying the names. You can do this by selecting the menu File>Preferences>Guide and checking the box labeled “Show names in component palette”. Click on the “TXT” button and then click the drawing area in the upper portion. A “Static text” box appears. You can resize it by dragging the mouse. Alternatively, you may drag the mouse instead of clicking to get a box of required size. Double click on the static text box to invoke its property inspector. Various properties are alphabetically listed. Go to the “String” property and change it to”Exercise 1 – Adder”. Change the foreground color to red, font weight to “bold” and font size to 12. Using the “EDIT” button, place two edit boxes below the title. Place a static text box to the right to store the result. Again use the “TXT” button and place two static text boxes. Change their strings to “+” and “=” as described above. Place a push button at the bottom. Change its string to “ADD”. To make it look more dramatic, change its background color to green. Note that the GUI objects snap to the grid while placing. The default grid spacing is 50 pixels. You can change it through Tools>Grid and rulers menu. You can even disable the “snap to grid” property through Layout menu.

Now that all the GUI elements are in place, we need to write a code that should get invoked when the ADD button is pressed. From menu, select File>Save as and save it as “adder.fig’. MATLAB automatically generates and saves another file named “ADDER.M”. This file has a skeleton code already written. We need to add our desired action code to it. Each GUI object is associated with a callback function and a handle. The object properties can be accessed via the handle. The callback function gets hObjet as a parameter and it is the current object’s handle. This function also gets a very useful parameter, “handles”. This is a structure containing handles to all the GUI elements in the figure. It is useful in obtaining the handles of other objects in the system.

It is a good idea to initialize the two edit boxes with zeroes. From the property inspector, verify that the “Tag” properties of the two edit boxes are “edit1” and “edit2” respectively. Tag of the result static text box is “text5”. The handles of the GUI objects are identified by their tags. “handles.edit1” refers to the handle of the edit1 edit box. The strings in the edit boxes can be set with the statements:

This is achieved by adding following code to the adder_OpeningFcn.

set(handles.edit1,'String','0');

set(handles.edit2,'String','0');

When the ADD button is clicked, its callback function is called. The prototype of the pushbutton callback function appears at the bottom as:

function pushbutton1_Callback(hObject, eventdata, handles)

We will read the contents of the edit boxes with the statements:

a = get(handles.edit1,'String');

b = get(handles.edit2,'String');

The variables a and b are string type. They are converted to numeric with the str2num function. The answer is calculated with the statements:

total = str2num(a) + str2num(b);

The number total is converted to a string with num2str function with the statement:

c = num2str(total);

The answer is displayed with the statement:

set(handles.text5,'String',c);

Assignment 2

Use of sliders and list boxes

In this assignment, we will add two sliders to give input to the edit boxes and a list box to select the arithmetic operation.

Solution

Save the previous files as “adder2.fig” and “adder2.m”. Open guide. Using the “Open existing GUI” tab and the “browse” button, open adder2.fig. We want to achieve the following result.

Change the title to “Exercise 2 – calculator” by changing the string property of the static text box.

From the tool palette add two sliders to the figure. Add following lines in the slider1_Callback function.

v = get(hObject,'Value');%Get position of slider

s = num2str(v);%Convert it to string

set(handles.edit1,'String',s);%Display it in edit1 box

Add following lines in the slider2_Callback function.

v = get(hObject,'Value');%Get position of slider

s = num2str(v);%Convert it to string

set(handles.edit2,'String',s);%Display it in edit1 box

Note that the default range of the slider value is from 0 to 1. We can change it by setting the Min and Max properties in the property inspector.

Remove the “+” text box and replace it with a list box. Reduce its height and width. Reposition the other objects if necessary. In the property inspector, click the icon to the right of string property. This invokes the string array editor. Add symbols +, -, *, / on 4 different lines.

Change the String of the ADD button to CALCULATE.

Change its callback function as follows.

a = get(handles.edit1,'String');

b = get(handles.edit2,'String');

index_selected = get(handles.listbox1,'Value');

list = get(handles.listbox1,'String');

item_selected = list{index_selected}; % Convert from cell array

switch item_selected

case'+'

total = str2num(a) + str2num(b);

case'-'

total = str2num(a) - str2num(b);

case'*'

total = str2num(a) * str2num(b);

otherwise

total = str2num(a) / str2num(b);

end

c = num2str(total);

set(handles.text5,'String',c);

guidata(hObject, handles);

Now you can run the GUI by typing adder2 at the command prompt. The slider movement is reflected in the edit box. You can select the desired operation in the list box and the calculate button displays the result.

Exercise 3

Invoking simulink from GUI

Objective of this exercise is to build a simulink model of a damped mass spring system in simulink and specify the k and m parameters from GUI. We want to display the response of this system to a unit step function for F in the GUI.

This is a classic problem from mechanics. The differential equation for the displacement x(t) can be written as:

d2x dx

m ---- = F – c ---- - k x

dt2 dt

Where m = mass of the block, k = spring constant, c = friction coefficient and F is the external force. We will implement the function after dividing by m as follows.

d2x dx

---- = F – c/m ---- - k/m x

dt2 dt

Solution

Invoke simulink and create following model

The integrator block can be found in the continuous library and the output port block in the commonly used blocks library. The Add block has initially only two inputs. When you invoke its property editor and change the list of signs to +--, third input is added. Change the step time of the step block from 1 to 0. The gain of the gain blocks is entered as 1/m, c/m and k/m respectively. Here we assume that the variables m, c, k are stored in memory. We are going to set these variables from the gui. There is a small problem involved here because the workspace of gui is not the main workspace which simulink refers. We will solve this problem by changing the workspace of simulink with the simset command. Save the model as “mass_spring.mdl”. To avoid an irritating warning about setting step size, choose the menu Simulation>Configuration parameters from the model editor. Click on diagnostic entry in the left pane and make the option for “Automatic solver parameter selection” to “none”. Close the model editor and simulink library browser.

Invoke guide and create a figure as given below.

Change the tags of the sliders to slider_m, slider_c and slider_k. Similarly change the tags of the edit boxes as edit_m, edit_c and edit_k. Change the tag of the push button to pb_simulate and its string to “simulate”. Save the file as “spring_gui.fig”. MATLAB automatically generates and opens “spring_gui.m” file. The pb_simulate_Callback

Function should appear as follows.

axes(handles.axes1) %set the axes

m=str2num(get(handles.edit_m,'String')); %fetch the mass value

c=str2num(get(handles.edit_c,'String')); %fetch the damping value

k=str2num(get(handles.edit_k,'String')); %fetch the spring constant

%configure the options so that the current

%workspace is used in simulating the model

options = simset('SrcWorkspace','current');

%the sim command simulates the simulink model

%the first argument is the model name

%the second argument is an array containing the start and stop time

%if [] is used, then the value from within the simulink model is used

%the third argument is the options configured from simset

sim('mass_spring',[],options);

%plot the data

plot(tout,yout)

xlabel('Time')

ylabel('Displacement')

Title('2nd Order Mass Spring System')

grid on

Add following code to slider_m_Callback

v = get(hObject,'Value');

s = num2str(v);

set(handles.edit_m,'String',s);

Add similar code to other two slider callbacks.

Save the file and invoke it from the MATLAB command prompt by typing “spring_gui”. Give suitable values to m,c,k and press “Simulate button. Following screen should appear.

Exercise 4

Solving polynomial matrices with symbolic math

Consider the circuit shown below.

______

------|_1H__|------/\/\/\/\------

| | 2 ohm |

| --- |

| --- 1F |

| i1 | i2 |

| __|__ |

| --- 10V |

| | |

------|------

It is desired to build s-domain mesh equations, solve them and get time domain solution by taking the inverse Laplace transform

Solution

The mesh equations are:

s+1/s-1/s I1(s)=-10/s

-1/s2+1/s I2(s) 10/s

We start by defining s and t as symbols with the statement:

syms st;

This helps in defining polynomial expressions in “s” and doing multiplication operation on them. The “t” symbol is required for inverse Laplace transform. We solve the mesh equations for I1(s) and I2(s) by applying the Crammer’s rule. The answers are as follows.

I1(s) = -20/(2*s^2+s+2)

I2(s) = 10*s/(2*s^2+s+2)

Then we will get time domain solution in terms of “t” by using the” ilaplace” function. For getting a plot of i1(t) and i2(t) vs time, The answers are as follows.

i1(t) =-8/3*15^(1/2)*exp(-1/4*t)*sin(1/4*15^(1/2)*t)

i2(t) = 1/3*exp(-1/4*t)*(15*cos(1/4*15^(1/2)*t)-15^(1/2)*sin(1/4*15^(1/2)*t))

we use the subs(substitute) command where t is substituted by a vector x in the range of 0 to 20 seconds. The final plot is like this:

The complete program listing is given below.

clear all;close all;clc;

syms st;

Z = [s+1/s -1/s;-1/s 2+1/s];

d = det(Z)

n1 = [-10/s -1/s;10/s 2+1/s];

dn1 = det(n1);

n2 = [s+1/s -10/s;-1/s 10/s]

dn2 = det(n2)

i1 = dn1/d

i1t = ilaplace(i1)

i2 = dn2/d

i2t = ilaplace(i2)

x = 0:.5:20;

y1= subs(i1t,t,x);

y2 = subs(i2t,t,x);

plot(x,y1,x,y2);

Assignment 5 AM and FM demo

This GUI based program allows you to change modulation index(m), carrier frequency(fc) and modulating frequency(fm) by sliders and choose the modulation method by grouped radio buttons. Start guide and create following gui and call it “am”.

Using the property inspector, set the minimum and maximum limits of the sliders as follows.

SliderTagMinimumMaximum

Mod indexslider102

Carr freqslider24001000

Mod freqslider320200

Save the gui so that “am.m” file is generated. It is a good idea to set some initial values to the sliders. To do this, add following lines at the end of the am_OpeningFcn

set(handles.slider1,'value',.5);

set(handles.slider2,'value',600);

set(handles.slider3,'value',50);

The radio button state can be checked with the “get” function as follows.

rb_am = get(handles.radiobutton1,'value');

If the button is checked, it returns 1, else 0. Calculation of AM and FM values is self explainatory.

Write a new function “calculate” as follows.

function calculate(handles)

m = get(handles.slider1,'value');

fc = get(handles.slider2,'value');

fm = get(handles.slider3,'value');

set(handles.edit1,'String',num2str(m));

set(handles.edit2,'String',num2str(fc));

set(handles.edit3,'String',num2str(fm));

t= linspace(0,.025,1024);

rb_am = get(handles.radiobutton1,'value');

y1 = (1+ m * cos(2 * pi * fm * t));

y2 = sin( 2 * pi * fc * t);

if rb_am == 1

y = y1 .* y2;

else

y = zeros(1024,1);i=1;

for time = t

y(i) = sin( 2 * pi * fc * time + m * sin(2 * pi * fm * time));

i = i+1;

end

end

f = abs(fft(y,32768));

axes(handles.axes1) %set the axes

plot(y1);

axes(handles.axes2) %set the axes

plot(y2);

axes(handles.axes3) %set the axes

plot(y);

axes(handles.axes4) %set the axes

plot(f(1:1600));

Add following line to the slider callback functions.

calculate(handles);