- Undocumented Matlab - https://undocumentedmatlab.com -

handle2struct, struct2handle & Matlab 8.0

Posted By Yair Altman On December 29, 2010 | 11 Comments

Last week I explained that FIG files are simply MAT files in disguise [1]. 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.


Under the hood, hgsave uses the semi-documented [2] 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.


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 [3]? 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.');
    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.');
    if SaveOldFig
        hgS = hgsaveStructClass(h);
        SaveVer = '080000';
        hgO = hgsaveObject(h);
        SaveVer = '080000';
% 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 [4].
Let the upcoming 2011 be a year filled with revelations, announcements and fulfillment! Happy New Year everybody!

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

11 Comments (Open | Close)

11 Comments To "handle2struct, struct2handle & Matlab 8.0"

#1 Comment By Jason On January 3, 2011 @ 07:29

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


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 Comment By matt dash On January 11, 2011 @ 14:17

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


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.

#3 Comment By matt dash On January 11, 2011 @ 14:23

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

#4 Comment By matt dash On January 11, 2011 @ 15:18

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!

#5 Comment By Nievinski On May 19, 2011 @ 09:13

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.

#6 Comment By Yair Altman On May 19, 2011 @ 09:45

@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.

#7 Comment By Cameron Carroll On May 12, 2012 @ 15:07

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,


#8 Comment By Augusto Medeiros On June 9, 2014 @ 11:03

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:


That’s how I accomplished it.


#9 Comment By Manoj On October 29, 2014 @ 07:11

@Augusto – Your solution made my day!

#10 Pingback By Matlab installation take 2 | Undocumented Matlab On September 12, 2012 @ 06:08

[…] The new R2012b release has received the version ID of 8.0. Despite my speculations in 2010 (here and here) that Matlab 8.0 will bring along the promise of the much-awaited HG2, it turns out that I was wrong […]

#11 Pingback By Handle Graphics Behavior | Undocumented Matlab On March 6, 2013 @ 14:25

[…] The Serialize property is searched-for by the hgsaveStructDbl function when saving figures (I described hgsaveStructDbl here) […]

Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/handle2struct-struct2handle-and-matlab-8

URLs in this post:

[1] FIG files are simply MAT files in disguise: http://undocumentedmatlab.com/blog/fig-files-format/

[2] semi-documented: http://undocumentedmatlab.com/blog/legend-semi-documented-feature/#Semi-documented

[3] new HG2 mechanism: http://undocumentedmatlab.com/blog/matlab-hg2/

[4] comment: http://undocumentedmatlab.com/blog/handle2struct-struct2handle-and-matlab-8/#respond

[5] Undocumented scatter plot behavior : https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior

[6] FIG files format : https://undocumentedmatlab.com/articles/fig-files-format

[7] Matlab layout managers: uicontainer and relatives : https://undocumentedmatlab.com/articles/matlab-layout-managers-uicontainer-and-relatives

[8] Matlab's HG2 mechanism : https://undocumentedmatlab.com/articles/matlab-hg2

[9] Matlab and the Event Dispatch Thread (EDT) : https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt

[10] Types of undocumented Matlab aspects : https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects

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

[12] : https://www.mathworks.com/matlabcentral/newsreader/view_thread/300680

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.