handle2struct, struct2handle & Matlab 8.0

Last week I explained that FIG files are simply MAT files in disguise. Today, we look under the hood of Matlab’s hgsave function, which is used to save FIG files. We shall see that this is both useful and illuminating vis-a-vis Matlab’s future.

handle2struct

Under the hood, hgsave uses the semi-documented built-in handle2struct function to convert the figure handle into a Matlab struct that is then stored with a simple save (the same function that saves MAT files) function call.

The fact that handle2struct is semi-documented means that the function is explained in a help comment (which can be seen via the help command), that is nonetheless not part of the official doc sections. It is an unsupported feature originally intended only for internal Matlab use (which of course doesn’t mean we can’t use it).

handle2struct merits a dedicated mention, since I can envision several use-cases for storing only a specific GUI handle (for example, a uipanel, a specific graph, or a set of GUI controls’ state). In this case, all we need to do is to call handle2struct with the requested parent handle, then save the returned structure. So simple, so powerful. handle2struct automatically returns all the non-default property information, recursively in all the handle’s children.

Note that features that are not properties of displayed handles (camera position, 3D rotation/pan/zoom states, annotations, axes-linking etc.) are not processed by handle2struct. For storing the states of these features, you need to use some specific handling – see the code within %matlabroot%\toolbox\matlab\graphics\private\hgsaveStructDbl.m for details. Basically, hgsaveStructDbl.m reads the state of all these features and temporarily stores them in the base handle’s ApplicationData property; handle2struct then reads them as any other regular handle property data, and then hgsaveStructDbl.m clears the temporary data from the handle’s ApplicationData. We can use the same trick for any other application state, of course.

struct2handle

handle2struct has a reverse function – the semi-documented struct2handle. I use it for creating dynamic preference panels: As in Matlab’s Preferences window, I have a list of preference topics and a set of corresponding options panels. In my case, it was easy to design each panel as a separate FIG file using GUIDE. In run-time, I simply load the relevant panel from its FIG file as described above, and place it onscreen in a dedicated uipanel using struct2handle. This enables very easy maintenance of preference panels, without sacrificing any functionality.

Matlab's preferences panels

Matlab's preferences panels

Figure menus and toolbars are not normally stored by hgsave, unless you use the optional ‘all’ parameter (and correspondingly in hgload, if you choose to use it). handle2struct and handle2struct accept the same optional ‘all’ parameter as hgsave and hgload. Unfortunately, a warning message indicates that this option will be discontinued in some future Matlab version.

Which brings us to our final topic for today:

Matlab 8: Boldly going where no FIG has gone before…

Remember my post earlier this year about the new HG2 mechanism? I speculated that when MathWorks decides to release HG2, it will define this as a major Matlab release and label it Matlab 8.0.

The source code in hgsave.m appears to confirm my speculation. Here is the relevant code section (slightly edited for clarity), which speaks for itself:

% Decide which save code path to use
if ~feature('HGUsingMatlabClasses')   % <== existing HG
    % Warn if user passed in 'all' flag
    if SaveAll
        warning( 'MATLAB:hgsave:DeprecatedOption', ...
            'The ''all'' option to hgsave will be removed in a future release.');
    end
    hgS = hgsaveStructDbl(h, SaveAll);
    SaveVer = '070000';
    SaveOldFig = true;
 
else   % <== HG2
 
    % Warn if user passed in 'all' flag
    if SaveAll
        warning( 'MATLAB:hgsave:DeprecatedOption', ...
            'The ''all'' option to hgsave has been removed.');
    end
    if SaveOldFig
        hgS = hgsaveStructClass(h);
        SaveVer = '080000';
    else
        hgO = hgsaveObject(h);
        SaveVer = '080000';
    end
end
 
% Revision encoded as 2 digits for major revision,
% 2 digits for minor revision, and 2 digits for
% patch revision.  This is the minimum revision
% required to fully support the file format.
% e.g. 070000 means 7.0.0

As can be seen, when Matlab starts using HG2 (perhaps in 2011?), the top-level structure node will be called “hgS_080000″, indicating Matlab 8.0. QED.

As a side-note, note that in HG2/Matlab8, although the comment about using ‘all’ indicates that it has been removed, in practice it is still accepted (although not being used). This will enable your code to be backward-compatible whenever HG2 launches, and future-compatible today.

Have you used handle2struct or struct2handle? If so, please share your experience in a comment.

Let the upcoming 2011 be a year filled with revelations, announcements and fulfillment! Happy New Year everybody!

Related posts:

  1. Matlab layout managers: uicontainer and relatives Matlab contains a few undocumented GUI layout managers, which greatly facilitate handling GUI components in dynamically-changing figures....
  2. Matlab and the Event Dispatch Thread (EDT) The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  3. Types of undocumented Matlab aspects This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...
  4. FIG files format FIG files are actually MAT files in disguise. This article explains how this can be useful in Matlab applications....
  5. Handle Graphics Behavior HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...
  6. Matlab DDE support Windows DDE is an unsupported and undocumented feature of Matlab, that can be used to improve the work-flow in the Windows environment...

Categories: Handle graphics, Medium risk of breaking in future versions, Semi-documented function, Stock Matlab function

Tags: , , , , , , ,

Bookmark and SharePrint Print

10 Responses to handle2struct, struct2handle & Matlab 8.0

  1. Jason says:

    Another Matlab 8 clue? A to-be-released book:

    http://www.amazon.com/Mastering-Matlab-Duane-C-Hanselman/dp/0136013309

    Just to be sure that it wasn’t a “new volume number” I looked at the last one, which came out the same time frame as the release of Matlab 7 (R14).

  2. matt dash says:

    As a mildly interesting related note, I just noticed that the problem I described here:

    http://www.mathworks.com/matlabcentral/newsreader/view_thread/300680

    Does not occur if I use the version 8 option in hgsave (by removing the ~ in “if ~feature(‘HGUsingMatlabClasses’)”) so that it uses hgsaveStructClass instead of hgsaveStructDbl.

    • matt dash says:

      edit: Actually I also needed to ~ the “if SaveOldFig”, so it is using hgsaveObject, not hgsaveStuctClass, when it works without errors.

    • matt dash says:

      On third thought, that still didn’t quite fix the problem. The saving worked, but I got an error when trying to re-open it, thus defeating the purpose of saving it…

      I did end up fixing my original problem by making a simplified version of hgsave that uses handle2struct to get all the info that would normally be saved in a .fig file, and then I removed the references to the jtable before saving the stucture. Works like a charm!

  3. Nievinski says:

    I discovered recently both functions and started to use them. I’m developing a program with an interface that uses tabs, so to organize all the tabs is better to keep them isolated, so i’m using diferent figures and calling them in the main figure using handles2struct followed by struct2handle. Besides i’ll need this feature to some other tasks. Can you say about the chances of these function be removed in future releases? That would be disastrous for me.

    • @Nievinski – I personally think that these two functions will not be removed anytime soon. However, their internal implementation may indeed change. Also, I do not get any inside information from MathWorks, so I could be wrong in my assumptions.

  4. Cameron Carroll says:

    I’m trying to use struct2handle to generate figures from a common base figure (loaded as a structure as per these blog posts) but I don’t really understand what to declare the parent as. struct2handle complains if I just pass it a struct, and the function itself doesn’t really return any meaningful error messages. [struct2handle(figstruct, gcbf) => 'Caught unexpected error of unknown type.']

    I was just wondering what to pass in as the parent parameter, and whether anyone has an example.

    Thanks a ton,

    Cameron

    • Augusto Medeiros says:

      Hi, I know your post is 2 years old, but wondered it might help someone else with the same problem, since this information is not easily found on the internet. After loading your figure as a structure named ‘s’, you should do:

      struct2handle(s.hgS_070000,0,'convert');

      That’s how I accomplished it.

      Cheers,
      Augusto

  5. Pingback: Matlab installation take 2 | Undocumented Matlab

  6. Pingback: Handle Graphics Behavior | Undocumented Matlab

Leave a Reply

Your email address will not be published. Required fields are marked *

*

<pre lang="matlab">
a = magic(3);
sum(a)
</pre>