Monthly Archives: July 2013

Getting Started with GUIs using GUIDE

Guide is a simple tool in Matlab to swiftly create custom GUIs. Its a GUI to create a GUI, but needs some coding to get it working. In today’s blog I’ll show how to make some simple GUIs with Guide. Once you get the gist of the technique you will be playing around with GUIs in no time.

Type guide at the Matlab prompt and choose blank template at the query. The interface you see should like the one below.

Matlab GUIDE

The panel on the left shows you all the various kinds of objects you can create in a Matlab GUI viz., pushbuttons, togglebuttons, radiobuttons, edit fields, text strings, checkboxes, axes, dropdown/popup menu, listboxes, tables, sliderbars, and a panel to create groups of these objects. To keep it simple, I’ll demonstrate building a GUI for a basic task like multiplying two numbers, say speed and time to yield distance.

Guide Example

Creating the interface should be just drag-and-drop task. To edit the strings on the objects, double-click on them to open up property-inspector. Change the value of field called “string” from the default one to the one you want.

GUIDE Inspector

So I ‘ve 3 edit-fields, 3 static-texts, and a pushbutton as shown below. As user enters numbers in speed and time edit fields and pushes the pushbutton, the distance value is calculated and displayed. These are the objects, their tags and values in my GUI:

Object

Tag

Value/string

Text string for SPEED

text1

Speed

Text string for TIME

text2

Time

Text string for DISTANCE

text3

Distance

Edit field for SPEED

edit1

0

Edit field for TIME

edit2

0

Edit field for DISTANCE

edit3

0

Pushbutton

pushbutton1

Calculate

Now save the gui with a valid name and run it. You would be seeing the interface with the objects you put. Also notice that Matlab creates two files with the filename you used – a .fig file and an .m file. You may try using the GUI but it doesn’t yet work. That’s because although the objects exist they haven’t been programmed to communicate with each other, which will be the next task.

To understand how GUIs work in Matlab one must understand two things. First, graphics in Matlab are managed by means of what are called handles. Every window/interface that Matlab creates gets a handle. E.g. your main Matlab window has the handle 0 (numeric zero). Handles (as of 2013a) can be positive integers or fractions (it can be controlled if an object should get an integer handle). Think of handles as addresses for graphical objects. Second, GUI objects are associated with event functions which are automatically invoked when an event occurs. E.g. clicking on a pushbutton, changing value in a text field, toggling a toggle button, switching a radio button, etc are all events that trigger execution of a designated function called “callback function”. It’s the callback functions that pour life into a GUI. When you create an object in your GUI using Guide, Matlab automatically creates a placeholder template in the m-file for callback linked to the object. The name of the callback function will bear the tag of the object. E.g. for an object with tag “pushbutton1″ you will see a function with definition function pushbutton1_Callback(hobject,eventdata,handles) .

This function is automatically invoked when pushbutton1 of the GUI is clicked on. Hence, whatever action the function is coded to carry out will be performed. During the callback hobject will have handle to the object whose callback is being executed, which is a very handy thing to have. eventdata is blank and left unused often, and handles is a structure containing handles of all the objects placed in the GUI. E.g. handles.pushbutton1 will have handle to the object with tag pushbutton1.

In our example, we need only one action: to calculate the product of the numbers and display inside the edit field corresponding to ‘Distance’, when user clicks on the “Calculate” pushbutton. We will hence define only the pushbutton’s callback function. In the m-file, scroll down to locate pushbutton1_Callback and place the following code.

function pushbutton1_Callback(hObject, eventdata, handles)
speed_string = get(handles.edit1,'value');
time_string = get(handles.edit2,'value');
speed_val = str2double(speed_str);
time_val = str2double(time_str);
distance_val = speed_val * time_val;
distance_string = num2str(distance_val);
set(handles.edit3,distance_string);

get function fetches value of a particular property of the object specified by the field. Its syntax is get(handle,’property_name’). In the above code, we are fetching the strings in the two edit fields, converting them to numbers and multiplying them. Conversion to numbers can be done by str2double or str2num. Then we use put function to write a value to the specified property with the following syntax - put(handle,’property_name’,'value’). Note that value is in quotes only if the property takes a string rather than a number as is the case with text edit fields, static texts, pushbuttons, etc. In case of radiobuttons and checkboxes value is either 0 or 1 denoting whether or not the button is OFF or ON.

As the callback finishes execution, the GUI has new string in the distance field. Note that we didn’t bother about callback functions for edit fields which are invoked when user changes value in the field. For a novice, it would be a good exercise to enhance the above GUI to update the distance field as soon as user changes value in speed or time field. Such a design obviates “Calculate” pushbutton.

You might also see a lot of other placeholders functions created in the m file like createfunctions, etc which are automatically created by GUI. If you don’t intend to use them, you can get rid of them by deleting their references in property inspector, but deleting them from m-file directly is a bad idea. This is one of the drawbacks of Guide – it messes up m-file quite a bit. Guide is good in cases where you anticipate your GUI to continuously evolve in design and is has moderate complexity. Guide is a nice, expedites GUI design & layout, but is still a clumsy tool. GUIs created by it tend to be slightly slower in response compared to those created manually. I’d prefer to use Guide to quickly show my client the concept but would avoid it in cases of very complex GUIs with a lot of objects or where the specs/requirements aren’t changing. Creating GUIs without Guide involves creating the figure, objects, etc manually using functions like uicontrol. Planning a GUI layout with manual design could be time-consuming, needs some patience and practice and is worth only if the GUI is too complex for Guide to handle.

I would be happy to answer your questions on Guide/GUIs. How do you design your GUIs? Share your experiences, tips for our readers. Leave a question/comment below.

Writing Efficient Matlab Code by Vectorization

Let me start with an example – sum up all numbers in a 10000×10000 matrix (of the default type double), which would involve 100M floating point additions. Look at the two implementations below:

% Code A:
x = randn(1e4);
s=0;
tic
for i=1:1e4
for j=1:1e4
s=s+x(i,j)*x(i,j);
end
end
toc

Avg Time Taken* : 2.2s

% Code B:
s=0; tic, s = sum(x(:)); toc

Avg Time Taken* : 0.06s

* on a 2.5Ghz Intel Core-I5 with R2011a running on OS 10.8

It can be seen that Code-A takes whopping 36 times longer than Code-B to do the same task. The reason B is faster is because it does a vectorised addition in contrast to a repetitive addition by loops of A.

Vectorization is akin to batch processing – its lot faster to execute a task on bunch of numbers than executing the same task individually on the same bunch of numbers. This is not really any magic, but an exploitation of processor architecture with some smart coding. Think of it like time taken for you to fetch groceries all in one go versus the time taken if you had to visit the store once for every item on your wife’s list.

Another example – Get averages of every two successive numbers in an array. i.e. if x = [0,1,2,3,4,5] create a y which is [0.5,1.5,2.5,3.5,4.5]. It might be tempting to put a loop for the purpose, but it can be done much more elegantly using indexing as follows.

y = (x(1:end-1)+x(2:end))/2;

Another example: evaluating a function in 2 independent variables over a given 2D space. Let the function be the Sinc function given as f(x,y) = { sin((x^2+y^2)^0.5) } / ((x^2+y^2)^0.5) in the space [-2pi, 2pi].

[x,y] = meshgrid(-2*pi:0.1:2*pi,-2*pi:0.1:2*pi);
z = sin(sqrt(x.^2+y.^2)) ./ (sqrt(x.^2+y.^2))

In real world problems, vectorization makes day and night difference. It could be so pronounced for a computationally intensive task that one might have to wait for days in contrast to waiting a few minutes with vectorization exploited. Vectorising has no syntaxes per se, its just an art of utilising some cool features, operators and builtin functions. E.g  . (the dot) operator for element-wise operations, functions like repmat, reshape. It’s a skill that you nurture with some practice.

Loops are inherently inefficient in Matlab, but they have come a long way in the last 8 years or so, thanks to JIT compiler (see the 4th comment in the article here). Loops however cannot be ditched altogether. There would be situations where using a loop becomes inevitable to realise some logic (e.g. in cases where current computation depends on previous computation). Its would be a good habit for budding Matlab programmers to think on lines of vectorization and resort to loops only as last option. Vectorization has a downside too. It’s demanding on memory and if computations  push the machine to limits with “out of memory” errors you might want to have a relook at vectorization strategy. You might have to reduce the amount of vectorization in favour of loops (with better memory management) to strike a good balance between speed of execution and memory demand.

I would love to see your comments. Share your experiences with vectorization.