Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

handle2struct, struct2handle & Matlab 8.0

December 29, 2010 11 Comments

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

% 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. Undocumented scatter plot behavior – The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....
  2. FIG files format – FIG files are actually MAT files in disguise. This article explains how this can be useful in Matlab applications....
  3. Matlab layout managers: uicontainer and relatives – Matlab contains a few undocumented GUI layout managers, which greatly facilitate handling GUI components in dynamically-changing figures....
  4. Matlab's HG2 mechanism – HG2 is presumably the next generation of Matlab graphics. This article tries to explore its features....
  5. 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....
  6. Types of undocumented Matlab aspects – This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...
GUIDE Handle graphics HG2 Hidden property Menubar Pure Matlab Semi-documented function Toolbar
Print Print
« Previous
Next »
11 Responses
  1. Jason January 3, 2011 at 07:29 Reply

    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 January 11, 2011 at 14:17 Reply

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

    https://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 January 11, 2011 at 14:23 Reply

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

      • matt dash January 11, 2011 at 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!

  3. Nievinski May 19, 2011 at 09:13 Reply

    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.

    • Yair Altman May 19, 2011 at 09:45 Reply

      @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 May 12, 2012 at 15:07 Reply

    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 June 9, 2014 at 11:03 Reply

      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');

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

      That’s how I accomplished it.

      Cheers,
      Augusto

      • Manoj October 29, 2014 at 07:11

        @Augusto – Your solution made my day!

  5. Matlab installation take 2 | Undocumented Matlab September 12, 2012 at 06:08 Reply

    […] 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 […]

  6. Handle Graphics Behavior | Undocumented Matlab March 6, 2013 at 14:25 Reply

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

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (email)
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Marcel (9 days 18 hours ago): Hi, I am trying to set the legend to Static, but this command seems not to work in R2022a anymore: set(gca,’LegendColorbarL isteners’,[]); Any ideas? THANKS / marcel
  • Gres (9 days 21 hours ago): In 2018b, you can get the icons by calling [hh,icons,plots,txt] = legend({‘Line 1’});
  • Yair Altman (11 days 16 hours ago): @Mitchell – in most cases the user wants a single string identifier for the computer, that uniquely identifies it with a distinct fingerprint that is different from any...
  • Mitchell (12 days 1 hour ago): Great post! I’m not very familiar with the network interfaces being referenced here, but it seems like the java-based cross-platform method concatenates all network...
  • Yair Altman (14 days 19 hours ago): Dani – You can use jViewport.setViewPosition(java .awt.Point(0,0)) as I showed in earlier comments here
  • dani (15 days 14 hours ago): hi!! how i can set the horizontal scrollbar to the leftside when appearing! now it set to right side of text
  • Yair Altman (24 days 11 hours ago): Dom – call drawnow *just before* you set hLine.MarkerHandle.FaceColorTy pe to 'truecoloralpha'. Also, you made a typo in your code: it’s truecoloralpha, not...
  • Dom (25 days 9 hours ago): Yair I have tried your code with trucoloralpha and the markers do not appear transparent in R2021b, same as for Oliver.
  • Yair Altman (28 days 17 hours ago): Ren – This is usually the expected behavior, which avoids unnecessary duplications of the Excel process in CPU/memory. If you want to kill the process you can always run...
  • Yair Altman (29 days 6 hours ago): When you use plot() without hold(‘on’), each new plot() clears the axes and draws a new line, so your second plot() of p2 caused the first plot() line (p1) to be...
  • Cesim Dumlu (35 days 14 hours ago): Hello. I am trying to do a gradient plot for multiple functions to be displayed on the same axes and each one is colorcoded by respective colordata, using the same scaling. The...
  • Yair Altman (43 days 17 hours ago): @Veronica – you are using the new version of uitree, which uses HTML-based uifigures, and my post was about the Java-based uitree which uses legacy Matlab figures. For...
  • Veronica Taurino (43 days 17 hours ago): >> [txt1,txt2] ans = ‘abrakadabra’
  • Veronica Taurino (43 days 18 hours ago): Hello, I am just trying to change the uitree node name as you suggested: txt1 = 'abra'; txt2 = 'kadabra'; node.setName([txt1,txt2]); >> "Unrecognized method, property, or...
  • Yair Altman (46 days 17 hours ago): The version of JGraph that you downloaded uses a newer version of Java (11) than the one that Matlab supports (8). You need to either (1) find an earlier version of JGraph that...
Contact us
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top