MATLAB - Global Variables

Matlab LogoHow do global variables differ from regular (local) variables?

Each function in MATLAB contains a set of variables specific to that function.  Even in the same .m file, you don’t have (direct) access to variables created in other functions within the file.  Global variables give you the ability to create/change a variable in one function and have that updated variable accessible elsewhere.  This post will discuss two methods for handling (no pun intended) global variables, one of which is perfectly integrated into Graphical User Interfaces (GUIs).

METHOD 1: global VARIABLE

The first (non-GUI) way to create a global variable is to use the function ‘global’.  Create the global variables X, Y, and Z with the command:

global  X Y Z

The ‘global’ function needs to be called in each separate function (usually in the beginning) where the variables will be called.   Stylistically, the variable names are usually longer names and all in CAPS to indicate global variables within the functions.  The documented example in the MATLAB helps shows this pretty well:

function tic
global TICTOC %define/incorporate global variable at start of function
TICTOC = clock;

function t = toc
global TICTOC %accesses variable TICTOC (or creates it if TICTOC is undefined)
if nargout < 1
    elapsed_time = etime(clock, TICTOC)
else
    t = etime(clock, TICTOC);
end

Many hard-core coders prefer to avoid using ‘global’ except for constants.  The reason behind this is because it’s generally considered poor form to lock up a variable name (See Steve L’s comment below for another reason!).  While this won’t matter for smaller programs and functions, when the files get to be many hundreds (or thousands or millions) of lines long, it can be very difficult to keep track of all of the global variables and to remember to call all the necessary variables at the start of each function.  The great thing about GUIs is that they already have a built-in global structure to deal with all of your global variables: the handles.  The handles structure is an input (and therefore accessible) to every function in the GUI, making it perfectly capable doing everything the ‘global’ command can.  In fact, you shouldn’t ever have to use ‘global’ command when designing a GUI because the handles structure does the job so well.  GUIs and ‘global’ don’t mix kids!

METHOD 2: handles.variable

As you may have seen from many of the blinkdagger GUI tutorials, the handles structure is an extremely useful method to manipulate GUI boxes/buttons/tools.  But the tool data are all just stored variables that can be accessed anywhere within the GUI (aka global variables!).  Since we don’t need to edit any ‘property’ of the handles structure (e.g. handles.static_text, ‘String’), we don’t need to use the ‘get’/’set’ commands.  Creating the global variable is as easy as saying:

handles.x = 42;
%And of course, don't forget to update your handles structure:
guidata(hObject, handles);

handles.x is now an independent variable and note that it has no relation to the local variable x.

x = 43;

is a completely valid command in the same function that would not overwrite your global variable ‘handles.x’.

Remember, these variables can range from constants (e.g. 12) to strings (e.g. ‘Hello World’) to structures, cells, and arrays of constants/strings.

Hopefully you can see the usefullness of global variables and will use them (properly!) in your coding adventures.

delicious bookmark StumbleUpon technorati Digg reddit icon rss icon

MMM #34 Winner, Sander Land!!!

MMM #32 Winner

mmmwin.jpg

The winner for the last MMM at Blinkdagger is Sander Land. A lot of you mistook this problem for the classic bridge/flashlight problem, but it was actually a little more complicated than that one. You can view the problem statement here. As mentioned previously, this is the last MMM to be conducted here at blinkdagger. We appreciate everyone for participating in this contest. It was a lot of fun while it lasted and we hope that there will be many new puzzles to solve over at wildaboutmath.com! Good luck to all!

The Answer by Sander Land

First, simply consider a general strategy for crossing the bridge.
It is clear that
- both Daniel and Quan need to use the bike at some point
- Sol needs to be the one to transfer the bike from one of them to the other.

This leaves a strategy like:
- Daniel takes the bike from the start to point x1, dismounting, and
continues to walk.
- Sol walks to point x1, and takes the bike back to point x2, and
walks to the end point.
- Quan walks to point x2, picks up the bike, and bikes to the end.

Taking into account the fact that any solution which has
- one of them arrive earlier than the others or
- one of them waiting at any time (including t=0)
can be improved, and normalizing the length of the bridge to 1, the
equations for this are:

D: x1 + 15*(1-x1) = T
Q: 8*x2 + (1-x2) = T
S: 3 + 4*(x1-x2) = T (i.e. walking the entire length, and
both walking and biking x1-x2)

Which matlab can help us solve:
>> D=15; Q=8; S=3;
>> R=[-D -1 -S]‘
>> A=[-(D-1) 0 -1 ; 0 (Q-1) -1 ; (S+1) -(S+1) -1]
>> A\R
0.7692 => x1 is at 77% of the bridge length
0.4615 => x2 is at 46% of the bridge length
4.2308 => They can cross the bridge in about 4 minutes and 14 seconds.

The other possible strategy (Quan starts on the bike) can also be
tried by simply switching Daniel and Quan’s velocities. This results
in the same shortest time.
>> D=8; Q=15; S=3;
0.5385
0.2308
4.2308

delicious bookmark StumbleUpon technorati Digg reddit icon rss icon

Monday Math Madness #34: Crossing a Bridge

mmm
Hey everyone, this is the last iteration of Monday Math Madness at Blinkdagger. We hope you guys all had fun for the past year or so. Good luck to all! Without further ado . . . here is the final problem!

The Problem Statement

Daniel, Quan, and Sol need to cross a bridge. Daniel can cross the bridge in 15 minutes, Quan can cross in 8 minutes, and Sol can cross in 3 minutes. There is also a bicycle available and any person can cross the bridge in 1 minute with the bicycle. What is the shortest time that all three people can get across the bridge?

Assume that each person travels at his own constant rate. In addition, assume that mounting and dismounting the bicycle is instantaneous.

Continue Reading »

delicious bookmark StumbleUpon technorati Digg reddit icon rss icon

MATLAB GUI Tutorial - UITABLE Part 2, How To Access Table Data

Matlab Logo Last time, we learned how to display data onto a table. This time, we’re going to learn how to work with table data within a GUI framework. For example, say you wanted to take the contents of the table manipulate the data. This tutorial will explain how to do that, and much more.

MATLAB UITABLE Tutorial 2

Contents

Accessing Table Data within GUI Callbacks

Let’s say you have the following GUI:

MATLAB UITABLE Tutorial 2

For simplicity sake, 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. How would you go about doing this? It’s actually quite straightforward. Let’s take a look at the callback for the add button:

function add_pushbutton_Callback(hObject, eventdata, handles)
% hObject    handle to add_pushbutton (see GCBO)
% eventdata  reserved - 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.uitable1,'data');

%add 3 to the table
tableData = tableData + 3;

%update the table
set(handles.uitable1,'data',tableData);

So now, when I press the “Add 3″ button, it adds 3 to the table! This is just a simple example to show how to extract the data from the UITABLE, and to perform an operation on it.

MATLAB UITABLE Tutorial 2

Accessing only the Selected Data

Now, let’s up the difficulty level a bit. Let’s say you selected a couple of cells that you want to sum, as shown in the image below (You can hold onto the CTRL button while clicking on individual cells to select multiple cells).

MATLAB UITABLE Tutorial 2

How would you go about doing this? Read on and all will be revealed.

Enabling CellSelectionCallback

The first thing we need to do is to enable the Cell Selection Callback. But first, why are we doing this? Enabling this callback will allow us to keep track of what cells are being selected on the table. You can do this by bringing up the Property Inspector for the UITABLE, and then clicking the following icon as shown in the image below.

MATLAB UITABLE Tutorial 2

If you did it correctly, your m-file should have been updated to include the following:

% --- Executes when selected cell(s) is changed in uitable1.
function uitable1_CellSelectionCallback(hObject, eventdata, 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, the CellSelectionCallback field should now be populated as shown in the image below:

MATLAB UITABLE Tutorial 2

Adding the Necessary Code

First, let’s create and initialize a variable to hold the table cell selection information. We will call this handles.selectedCells, and initialize it in the opening function.

% --- Executes just before uitable_tutorial_02 is made visible.
function uitable_tutorial_02_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - 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 = [];

Next, we go to the uitable1_CellSelectionCallback, which is the callback that we just enabled.

% --- Executes when selected cell(s) is changed in uitable1.
function uitable1_CellSelectionCallback(hObject, eventdata, 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 update this data
%eventdata stores the indices of the selected cells
handles.selectedCells = eventdata.Indices;

%update the gui data
guidata(hObject, handles);

Adding the Selected Numbers Together

First, we’re going to add another button and a static text component to display the sum. The modified GUI looks like this:

MATLAB UITABLE Tutorial 2

Now, we need to write the callback for the button we just added:

% --- Executes on button press in sumNumbers_pushbutton.
function sumNumbers_pushbutton_Callback(hObject, eventdata, handles)
% hObject    handle to sumNumbers_pushbutton (see GCBO)
% eventdata  reserved - 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,columns] = size(handles.selectedCells);

%get the data from the UITABLE
tableData = get(handles.uitable1,'data');

%initialize the sum
sum = 0;

%loop through each selected cell and keep a running sum
%can anyone thing of a better way to do this?
for x=1:rows
    sum = sum +tableData(tableIndices(x,1),tableIndices(x,2));
end

%display the sum on the GUI
set(handles.sum_text,'String',num2str(sum))

And there you have it, now you can select any number of cells, and then sum up the value of the contents!

MATLAB UITABLE Tutorial 2

Next Time

Next time, we’re going to talk about some of the cool features of the UITABLE that we have not yet discussed, including different data types within the UITABLE.

Links and Downloads

Download Source Files
The MathWorks Documentation for UITABLE
Cool Things You can do with UITABLE
Doug’s Video on UITABLE

delicious bookmark StumbleUpon technorati Digg reddit icon rss icon

MATLAB GUI Tutorial - UITABLE Part 1, How to Display Data

Matlab Logo With the release of MATLAB 2008b, you are now able to add tables to a GUI. In the past, there was no easy way to display your data in tabular form. With the UITABLE component, displaying your data in tabular form is easy, and most importantly, looks great!

MATLAB UITABLE

Contents

Adding a Table to Your GUI using GUIDE

Within the GUIDE framework, you can add a table to your GUI using the following icon from the toolbar: MATLAB UITABLE icon.

Here’s what the GUI will look like within GUIDE:

MATLAB UITABLE tutorial

Displaying Data on the Table

We are going to populate the UITABLE component with data by pushing the “Populate Table” button. Thus, we’re going to need to add some code to the pushbutton’s callback. In the populate_pushbutton callback, we use the following code:

% --- Executes on button press in populate_pushbutton.
function populate_pushbutton_Callback(hObject, eventdata, handles)
% hObject    handle to populate_pushbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%first, create a data matrix that has 5 columns, 4 rows
myData = rand(5,4);

%now populate the table with the above values
set(handles.uitable1,'data',myData );

Now, let’s run the GUI and push the button!

MATLAB UITABLE tutorial

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. So if I had done the following instead:

myData = rand(100,100);

The table would incorporate the use of scroll bars, as shown below.

MATLAB UITABLE tutorial

Adding Column and Row Labels

A good way to spruce up your table is to add row and column labels. This helps differentiate your data and makes it easy to identify. Within the GUIDE framework, we can modify the labels by first bringing up the Property Inspector for the UITABLE. This can be done by double clicking the UITABLE component.

Property Insepctor

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

Edit Row Labels

Make sure you click on the “Rows”, and that you select the “Show names entered below as the row headers” option. Finally, you just need to modify the names. Similarly, you can do the same for the columns.

MATLAB UITABLE tutorial

Once you’re done with that. you should see the following:

MATLAB UITABLE tutorial

And once you run your GUI, you can see the final result. A well labeled table that displays your data beautifully!

MATLAB UITABLE

Modifying your Table through the m-file

Sometimes it’s easier to work from within the m-file framework, rather than the GUIDE framework. We could have done exactly what we did above programmatically through the m-file. In the opening function we could have done the following:

%store the row headers into a cell array
rowHeaders = {'Blink','Dagger','Loves','MATLAB','!!!!!!'};

%set the row labels
set(handles.uitable1,'RowName',rowHeaders);

%do the same for the column headers
columnHeaders = {'Quan','Daniel','Rob','Zane'};
set(handles.uitable1,'ColumnName',columnHeaders);

In this example, we assumed that we knew the dimensions of our table. If you don’t know the size of your table beforehand, then it can be difficult to apply data labels that are meaningful. By working through the m-file, you obtain more flexibility since you won’t have to go back and modify the .fig file every time you want to make a change. And if you are going to apply dynamic labeling, then working from the m-file is going to be much easier.

Next Time

Next time, we’re going to talk about how to work with manipulating the data within the table.

Links and Downloads

Download Source Files
The MathWorks Documentation for UITABLE
Cool Things You can do with UITABLE
Doug’s Video on UITABLE

delicious bookmark StumbleUpon technorati Digg reddit icon rss icon

Next »