Loren on the Art of MATLAB

August 16th, 2006

Handle This!

I recently got a great request from a reader to discuss the various kinds of entities in MATLAB attached to the word handle. I want to talk about the parallels and differences of three affecting most MATLAB users:

And, of course, there's also George Frideric Handel

To hear more, try this in MATLAB:

               load handel
               sound(y,Fs)

Contents

Similarities

In all three cases, the handle or identifier let's you refer to another entity and possibly change its state, without creating a new variant.

  • For files, this means that I can read part of a file and advance through it while always being able to refer to that particular file.
  • Similarly, for graphics handles, I can change properties associated with the objects being referred, e.g., their colors, without changing how I refer to the graphics object itself.
  • Finally, for function handles, I can refer to a particular function via its handle even when conditions, such as the path or current directory, change. Also, for handles to nested functions, I am able to change the state of the function handle's workspace without needing to create a new way to refer to that particular instance of a function.

Differences

  • File handles and handle graphics objects all have top-level ways to locate them, even if they aren't assigned a variable in your current workspace.

Let me start by exploring a little bit about files.

fid1 = fopen('cumtrapz.m');
fid2 = fopen('trapz.m');
fid3 = fopen('mean.m');
clear

Now find the open files even though the workspace is empty.

fids = fopen('all')
fids =
     3     4     5

I have to close the files one at a time. Successful closure returns a 0. Make sure they all succeed.

success = 0;
if all(arrayfun(@fclose, fids)==0)
    disp('Success, all files closed')
else
    disp Oops!
end
Success, all files closed

Prove that no files are open.

fids = fopen('all')
fids =
     []

I can also use probe and manipulate within an open file using fseek and ftell to change and query the position indicator in the file.

Clear the workspace again, and any possibly lurking figures.

Next I will explore more about graphics handles by creating a plot and finding the line contained in the figure.

clear all
close all
load handel
t = (0:(numel(y)-1))/Fs;
plot(t,y)
title Handel
xlabel Seconds
clear

Now let me find the line I've drawn. I'll start by getting the children of the root from handle value 0. Then I'll get the axes, and finally the line inside.

figs = get(0,'Children')
ax = get(figs, 'Children')
handelLine = get(ax,'Children')
figs =
     1
ax =
  160.0015
handelLine =
  161.0034

To prove it's the same line, let me change the color. Notice that the handle itself has not changed value but the color property associated with it did.

set(handelLine,'Color','g')
handelLine
handelLine =
  161.0034

For function handles, I get use the functions function to query the state, possibly contained, for example, in a nested workspace. I cannot, however, directly change the state. I must use the function handle itself or some other function handle that has access to the nested workspace in order to affect a change.

  • File handles and handle graphics objects all have ways to dispose of them. For files, I simply use fclose, and for graphics objects, I delete them.

For function handles, I must delete every possible variable and callback that points to the handle in question to be sure that everything associated with the function handle has been purged.

Comparisons

File identifiers, handles to graphics objects, and function handles all use similar nomenclature and they share a lot of functionality and interaction in common. File identifiers and graphics objects can have persistence beyond the lifetime of the variables and programs that create them, whereas function handles last only until the last reference to them disappears. Please add your thoughts to these comparisons.


Published with MATLAB® 7.2

11 Responses to “Handle This!”

  1. junziyang replied on :

    I found that HANDLE is also a buit-in function of MATLAB but it is not documented! What’s the function of this function? How to use it? When should I use it?

  2. Loren replied on :

    Hi Junziyang-

    handle is an undocumented feature related to handle graphics for internal use at the moment so we can refactor some of the internal underpinnings and maintain compatibility.

    I doubt you should find a need for it.

    –Loren

  3. lehalle replied on :

    Do you think about a method to change the color (or any other property, like linewidth) of all the elements of a plot produce by a built-in function?

    for instance there is no way to specify the linewidth of the boxplot function, so I use something like that:

    figure;
    X = randn(100,1);
    plot(ones(size(X)),X,’.k’);
    c = get(gca,’children’);
    hold on
    boxplot(X);
    hold off
    bpc = setdiff(get(gca,’children’), c);
    set(bpc, ‘linewidth’,2, ‘color’, [0 .5 .5]);

    but for functions like candle, it cannot work because candle is made with lines and patchs (and patch do not have a color property), so I use a switch/case control on the object type…

    for candle it’s especially usefull because the original code (2006a) does not allow to change the color (it only changes the color of the patchs), cf:
    http://en.literateprograms.org/Matlab_Financial_Toolbox

    may be it is possible to ‘group’ handles like with something like ‘hggroup’ (but I did not had a lot of success with it) and then to change all properties at once?

    thanks
    charles

  4. lehalle replied on :

    you did not write anything about database and misc datasources (as financial data providers) connection handles. they are very heterogeneous (oracle, bloomberg, datastream, etc).

    rather than openning and closing those connections after each use, I choose to strore them into the get(0, ‘userdata’) property, they are in an hashtable indexed by any connection string that has been use and I close them before quiting matlab with a statement like your:

    all(arrayfun(@fclose, fids)==0)

    have you a point of view about that?

    regards
    charles

  5. Loren replied on :

    Personally I thinking storing information in ‘userdata’ is a poor idea. You’d be better off using a nested function and keeping a handle to the resource stored with the function handle. That way, you don’t stand a chance for userdata to get corrupted.

  6. Oliver A. Chapman, PE replied on :

    Loren,

    Another good topic to cover. Although, I suspect you only scratched the surface.

    How does a handle compare and contrast to a data structure?

  7. Kathirvel Thiyagarajan replied on :

    Respected Loren,

    I am receiving blog posts from Steve Eddins.
    Recently i came to know about your blog posts in steve blogs.
    But i am unable to subscribe to your blogs.
    Kindly help me.

  8. Loren replied on :

    Kathirvel-

    You should be able to subscribe in a similar way that you did for Steve’s. If you go to the right side in the blue area on my blog, you will see an area labeled Subscribe that has directions.

    –Loren

  9. Lassi replied on :

    I think that (online) documentation regarding handles related to plotting is quite poor and the handles get more complex if you do more complicated plottin. For instance, in a subplot with two plots, things can get really strange. If I try to access specifically the handle of the second subplot title, (figure.axes.title) I should get a cell array, but this only happens if I first try to get its parameters. I assume this is due to handlevisibility property set to off which effectively prevents me from accessing it.

    So, how am I supposed to manipulate the title of the second (or nth) subplot? No problem with the first…

  10. Jason replied on :

    Loren,

    Obviously this is 2 years later, but I found your statement saying you were not a “fan” of using UserData fields. I thought I might propose one reason that I think UserData might be appropriate.

    There have been some GUI instances where there is a pop-up menu with a list of options. Based on the selected option, a different parameter value is submitted to a function. Sometimes, the parameter value is an abbreviation, such as ‘deg’ for ‘Degrees’. Since I want to be formal with my GUI and spell out things fully in the pop-up, I find it useful to store the parameter values which correspond to the options in the UserData as an array or cell of strings. I guess I see it as a waste to have a variable dedicated to storing these because they only matter to that one particular task, and the Value property is used to index the parameter value array/cell in that particular callback.

    Jason

  11. Loren replied on :

    Jason-

    In a GUI, there are plenty of places to tuck such info without using UserData, e.g., AppData. That is less likely to get corrupted, imo…

    –Loren

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Jun: I totally can not believe it, Loren. You are really helpful. Thank you so much, MATLAB master!
  • Loren: Wow folks- Always lots of interest when there’s a quickie to try out! I will only make 2 general...
  • Loren: Jun- ismember is your friend here: >> [aa,ind] = ismember(Array2,Arra y1) aa = 1 1 1 1 1 1 1 ind = 1 2 1 4 4 3...
  • Dan: I like the first way better than the second way. Combining the arrays into one and running any is nice, although...
  • James Myatt: How about I = (a == 0 | b == 0); a(I) = []; b(I) = [];
  • Tunc: Hello Loren, love your blog because of such inspiring and challenging comments to such ’small’...
  • Pekka Kumpulainen: Here is my tradeoff. I usually want to keep the original variables as they are most probably...
  • Iain: Followup: Of course, to allow NaNs (counting them as non-zero): mask = (a~=0) & (b~=0); The mask says “a...
  • Matt Fig: I would usually go with something like this: y = a&b; x = a(y); y = b(y); But I was surprised to find...
  • kk: c=all([a;b]) a(c) a(b)

These postings are the author's and don't necessarily represent the opinions of The MathWorks.