<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>schema.prop &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/schemaprop/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Fri, 30 Sep 2022 14:59:20 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Matlab toolstrip – part 2 (ToolGroup App)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-2-toolgroup-app</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 05 Dec 2018 17:00:48 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[schema.prop]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8059</guid>

					<description><![CDATA[<p>Matlab users can create custom Apps with toolstrips and docked figures. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app">Matlab toolstrip – part 2 (ToolGroup App)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" rel="bookmark" title="Matlab toolstrip &#8211; part 1">Matlab toolstrip &#8211; part 1 </a> <small>Matlab contains extensive toolstrip (ribbon) functionality that can be integrated in user programs (GUI). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A while ago I posted the first of my planned miniseries on the <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">Matlab toolstrip (ribbon)</a>. Today I will expand that post by discussing how toolstrips can be added to Matlab GUIs. This post will remain at a high-level as the previous post, with followup posts drilling into the technical details of the toolstrip components (inner packages and classes).<br />
We can add a Matlab toolstrip to 3 types of Matlab GUI windows:</p>
<ol>
<li>To a Java-based Matlab figure (so-called &#8220;legacy&#8221; figures, created using GUIDE or the <i><b>figure</b></i> function)</li>
<li>To a container window of docked Java-based figures, typically called an &#8220;App&#8221; (marketing name) or &#8220;Tool Group&#8221; (internal technical name)</li>
<li>To a JavaScript/HTML-based Matlab figure (so called &#8220;web&#8221; figures, created using App Designer or the <i><b>uifigure</b></i> function)</li>
</ol>
<p>Today I will show how to add a basic dynamic toolstrip to a ToolGroup (App, window type #2):<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2c_animated.gif" alt="ToolGroup with clients and dynamic toolstrip" title="ToolGroup with clients and dynamic toolstrip" width="450" height="314" /><figcaption class="wp-caption-text">ToolGroup with clients and dynamic toolstrip</figcaption></figure></center><br />
<span id="more-8059"></span></p>
<h3 id="ToolGroup">Figure containers (&#8220;Tool Groups&#8221;)</h3>
<p>Most Matlab users are familiar with window types #1 and #3 (legacy and web-based figures), but type #2 may seem strange. In fact, it shouldn&#8217;t be: All the Matlab &#8220;Apps&#8221; and Desktop components use such a container of docked clients. For example, both the Matlab Editor and Desktop are containers of individual client windows (individual files in the Editor; Command Window, Workspace etc. in the desktop).<br />
Similarly, when we dock figures, they dock as client windows into a container called &#8220;Figures&#8221; (this can be controlled programmatically: see my <a href="https://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup" rel="nofollow" target="_blank"><i><b>setFigDockGroup</b></i> utility</a> on the File Exchange). This is the basis for all Matlab &#8220;Apps&#8221;, as far as I am aware (some Apps may possibly use a different GUI container, after all there are ~100 Matlab Apps and I&#8217;m not familiar with all of them). Such Apps are basically stand-alone Tool Groups (client container windows) that contain one or more docked figures, a toolstrip, and a side-panel with controls (so-called &#8220;Data Browser&#8221;).<br />
Note: MathWorks uses confusing terminology here, using the same term &#8220;App&#8221; for both MathWorks-created GUIs containers (that have toolstrips, Data Browser and docked figures) and also user-created utilities on the File Exchange (that do not have these). Unfortunately, MathWorks has chosen not [yet] to release to the general public its set of tools that enable creating true &#8220;Apps&#8221;, i.e. those that have a toolstrip, Data Browser and docked figures.<br />
Today&#8217;s post will attempt to fill this gap, by showing how we can create user Apps that have a toolstrip and docked figures. I will ignore the Data Browser today, and will describe it in a future post. Since docking figures into a standalone user-created container is a solved problem (using my <a href="https://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup" rel="nofollow" target="_blank"><i><b>setFigDockGroup</b></i> utility</a>), this post will focus on adding a toolstrip to such a container.<br />
A ToolGroup object (<code>matlab.ui.internal.desktop.ToolGroup</code>) is created either implicitly (by docking a figure into a group that has a new name), or explicitly (by invoking its constructor):</p>
<pre lang="matlab">
% Create a new non-visible empty App (Tool Group)
hToolGroup = matlab.ui.internal.desktop.ToolGroup('Toolstrip example on UndocumentedMatlab.com');
</pre>
<p>Some things only work properly after the app is displayed, so let&#8217;s display the ToolGroup (however, note that for improved performance it is better to do whatever customizations and GUI updates that you can before the app is made visible):</p>
<pre lang="matlab">
% Display the ToolGroup window
hToolGroup.open();
</pre>
<p><center><figure style="width: 435px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2b.png" alt="Basic empty ToolGroup (without toolstrip or clients)" title="Basic empty ToolGroup (without toolstrip or clients)" width="435" height="347" /><figcaption class="wp-caption-text">Basic empty ToolGroup (without toolstrip or clients)</figcaption></figure></center><br />
An annoying quirk with ToolGroups is that they automatically close when their reference handle is deleted from Matlab memory. The specific behavior changes depending on the contents of the container and the Matlab release, but in general it&#8217;s safest to preserve the <code>hToolGroup</code> variable, to prevent the window from closing, when this variable goes out of scope, when the function (in which we create the ToolGroup) returns. There are many ways to persist this variable. Here&#8217;s one alternative, in which we persist it in itself (or rather, attached to its internal Java peer control):</p>
<pre lang="matlab">
% Store toolgroup reference handle so that app will stay in memory
jToolGroup = hToolGroup.Peer;
internal.setJavaCustomData(jToolGroup, hToolGroup);
</pre>
<p><b><i>internal.setJavaCustomData</i></b> is an undocumented Matlab function that adds a new custom property to a Java reference handle. In our case, it adds a <b>CustomData</b> property to the <code>jToolGroup</code> handle and sets its value to the Matlab <code>hToolGroup</code> handle. The source code for <b><i>internal.setJavaCustomData</i></b> is available in <i>%matlabroot%/toolbox/shared/controllib/general/+internal/setJavaCustomData.m</i> and is very simple: it essentially uses the old <code>schema</code>-based <a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" target="_blank"><i><b>schema.prop</b></i></a> method for adding new properties to handles. <code>Schema</code> is an old deprecated mechanism that is mostly replaced by the newer MCOS (Matlab Class Object System), but for some specific cases such as this it&#8217;s still very useful (the standard <a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" target="_blank"><i><b>addprop</b></i> function</a> can add new properties to Matlab GUI handles, but not to Java reference handles).<br />
Finally, let&#8217;s discard the Data Browser side panel (I&#8217;ll discuss it in a separate future post):</p>
<pre lang="matlab">
% Discard the Data-browser left panel
hToolGroup.disableDataBrowser();
</pre>
<h3 id="toolstrip">Adding a toolstrip to the ToolGroup</h3>
<p>Now that we have the basic container ready, let&#8217;s add a toolstrip. To simplify matters in this introductory post (after all, I have still not described the internal packages and classes that make up a toolstrip), we&#8217;ll use some of the tabs used in the <code>showcaseToolGroup</code> example that I discussed in <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">my previous post</a>. You can see the relevant source code in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/*.m</i>, in case you want to jump ahead and customize your own toolstrip tabs, groups and buttons. In the code snippet below, we first create an empty <code>TabGroup</code>, then add toolstrip tabs into it, and finally add this <code>TabGroup</code> into our ToolGroup using its <i>addTabGroup(hTabGroup)</i> method:</p>
<pre lang="matlab">
% Create a new tab group
%hTabGroup = matlab.ui.internal.desktop.showcaseBuildTabGroup('swing');
hTabGroup = matlab.ui.internal.toolstrip.TabGroup();
hTab1 = matlab.ui.internal.desktop.showcaseBuildTab_Buttons('swing');
hTabGroup.add(hTab1);
%hTabGroup.add(matlab.ui.internal.desktop.showcaseBuildTab_Gallery());
hTabGroup.add(matlab.ui.internal.desktop.showcaseBuildTab_Layout('swing'));
% Select tab #1 (common)
hTabGroup.SelectedTab = hTab1;
% Add the tab group to the built-in toolstrip
hToolGroup.addTabGroup(hTabGroup);
</pre>
<p>We now have an &#8220;App&#8221; that has a toolstrip, but no clients (yet), and a hidden Data Browser side-panel:<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2a.png" alt='ToolGroup "App" with a simple toolstrip (no clients yet)' title='ToolGroup "App" with a simple toolstrip (no clients yet)' width="80%" style="max-width:673px;" /></center><br />
Now let&#8217;s add some clients (docked figures):</p>
<h3 id="clients">Adding clients (docked figures) to the ToolGroup</h3>
<p>There are two easy variants for adding docked figures in a ToolGroup: The easiest is to use the ToolGroup&#8217;s <i>addFigure(hFigure)</i> method:</p>
<pre lang="matlab">
% Create a figure and dock it into the tool-group
hFig1 = figure('Name','3D');
surf(peaks);
hToolGroup.addFigure(hFig1);
</pre>
<p>The second variant enables to dock a figure that has a specific set of toolstrip tabs attached to it. These tabs will only display in the toolstrip when that particular figure has focus. We do this by creating a new TabGroup (just as we have done above), and then add the figure and TabGroup to the container using the ToolGroup&#8217;s <i>addClientTabGroup(hFigure,hTabGroup)</i> method:</p>
<pre lang="matlab">
% Create the 2nd figure
hFig2 = figure('Name','2D');
plot(rand(5)); drawnow
% Add a few tabs that are only relevant to this specific figure
hTabGroup2 = matlab.ui.internal.toolstrip.TabGroup();
hTab2 = matlab.ui.internal.desktop.showcaseBuildTab_Selections();
hTabGroup2.add(hTab2);
hTabGroup2.add(matlab.ui.internal.desktop.showcaseBuildTab_EditValue());
% Add the figure and tabs to the ToolGroup
hToolGroup.addClientTabGroup(hFig2, hTabGroup2);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2c_animated.gif" alt="ToolGroup with clients and dynamic toolstrip" title="ToolGroup with clients and dynamic toolstrip" width="450" height="314" /><figcaption class="wp-caption-text">ToolGroup with clients and dynamic toolstrip</figcaption></figure></center><br />
In this example, the &#8220;Selection&#8221; and &#8220;Values&#8221; toolstrip tabs only appear when the 2nd figure (&#8220;2D&#8221;) has focus. A similar behavior exists in the Matlab Desktop and Editor, where some tabs are only shown when certain clients have focus.</p>
<h3 id="View">Removing the View tab</h3>
<p>Note that the &#8220;View&#8221; toolstrip tab (which enables setting the appearance of the docked figures: layout, tab positions (top/bottom/left/right), ordering etc.) is automatically added to the toolstrip and always appears last. We can remove this View tab using the ToolGroup&#8217;s <i>hideViewTab()</i> method. The tab will not immediately be removed, only when the toolstrip is repainted, for example, when we switch focus between the docked figures:</p>
<pre lang="matlab">
hToolGroup.hideViewTab;  % toolstrip View tab is still visible at this point
figure(hFig1);  % change focus to hFig1 - toolstrip is repainted without View tab
</pre>
<h3 id="conclusion">Conclusion</h3>
<p>It&#8217;s relatively easy to dock figures into a standalone &#8220;App&#8221; window that has a custom toolstrip, which can even be dynamically modified based on the figure which is currently in focus. Naturally, this has little benefit if we cannot customize the toolstrip components: labels, icons, control type, grouping and most importantly &#8211; callbacks. This topic deserves a dedicated post, which I plan to be the next in this miniseries. Stay tuned &#8211; hopefully the next post will not take me as long to publish as this post (I was quite busy recently)&#8230;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app">Matlab toolstrip – part 2 (ToolGroup App)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" rel="bookmark" title="Matlab toolstrip &#8211; part 1">Matlab toolstrip &#8211; part 1 </a> <small>Matlab contains extensive toolstrip (ribbon) functionality that can be integrated in user programs (GUI). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app/feed</wfw:commentRss>
			<slash:comments>17</slash:comments>
		
		
			</item>
		<item>
		<title>Adding custom properties to GUI objects</title>
		<link>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-custom-properties-to-gui-objects</link>
					<comments>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 15 Feb 2018 12:39:35 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7324</guid>

					<description><![CDATA[<p>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects">Adding custom properties to GUI objects</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab objects have numerous built-in properties (some of them publicly-accessible/documented and others not, but that&#8217;s a different story). For various purposes, it is sometimes useful to attach custom user-defined properties to such objects. While there was never a fully-documented way to do this, most users simply attached such properties as fields in the <b>UserData</b> property or the object&#8217;s [hidden] <b>ApplicationData</b> property (accessible via the documented <i><b>setappdata</b></i>/<i><b>getappdata</b></i> functions).<br />
An undocumented way to attach actual new user-defined properties to objects such as GUI handles or Java references has historically (in HG1, up to R2014a) been to use the undocumented <i><b>schema.prop</b></i> function, as I <a href="/articles/adding-dynamic-properties-to-graphic-handles" target="_blank">explained here</a>. As I wrote in that post, in HG2 (R2014b onward), we can use the fully-documented <a href="https://www.mathworks.com/help/matlab/ref/dynamicprops.addprop.html" rel="nofollow" target="_blank"><i><b>addprop</b></i> function</a> to add new custom properties (and methods) to such objects. What is still NOT documented, as far as I could tell, is that all of Matlab&#8217;s builtin handle graphics objects indirectly inherit the <code>dynamicprops</code> class, which allows this. The bottom line is that we can dynamically add custom properties in run-time to any HG object, without affecting any other object. In other words, the new properties will only be added to the handles that we specifically request, and not to any others.<br />
All this is important, because for some unexplained reason that escapes my understanding, MathWorks chose to seal its classes, thus preventing users to extend them with sub-classes that contain the new properties. So much frustration could have been solved if MathWorks would simply remove the <b>Sealed</b> class meta-property from its classes. Then again, I&#8217;d have less to blog about in that case&#8230;<br />
Anyway, why am I rehashing old news that I have already reported a few years ago?<br />
Well, first, because my experience has been that this little tidbit is [still] fairly unknown by Matlab developers. Secondly, I happened to run into a perfect usage example a short while ago that called for this solution: a <a href="https://stackoverflow.com/questions/48597836/matlab-figure-age" rel="nofollow" target="_blank">StackExchange user asked</a> whether it is possible to tell a GUI figure&#8217;s age, in other words the elapsed time since the figure was created. The simple answer would be to use <i><b>setappdata</b></i> with the creation date whenever we create a figure. However, a &#8220;cleaner&#8221; approach seems to be to create new read-only properties for the figure&#8217;s <b>CreationTime</b> and <b>Age</b>:<br />
<span id="more-7324"></span><br />
First, create a small Matlab function as follows, that attaches the CreationTime property to a figure:</p>
<pre lang="matlab">
function setCreationTime(hFig,varargin)
   hProp = addprop(hFig,'CreationTime');
   hFig.CreationTime = now;
   hProp.SetAccess = 'private';  % make property read-only after setting its initial value
   hProp = addprop(hFig,'Age');
   hProp.GetMethod = @(h,e) etime(datevec(hFig.CreationTime), clock);  % compute on-the-fly
   hProp.SetAccess = 'private';  % make property read-only
end
</pre>
<p>Now assign this function as the default CreateFcn callback function for all new figures from now on:</p>
<pre lang="matlab">
set(0,'DefaultFigureCreateFcn',@setCreationTime)
</pre>
<p>That&#8217;s it &#8211; you&#8217;re done! Whenever a new figure will be created from now on, it will have two custom read-only properties: <b>CreationTime</b> and <b>Age</b>.<br />
For example:</p>
<pre lang="matlab">
>> newFig = figure;
>> newFig.CreationTime
ans =
      737096.613706748
>> ageInDays = now - newFig.CreationTime
ageInDays =
       0.0162507836846635
>> ageDuration = duration(ageInDays*24,0,0)
ageDuration =
  duration
   00:23:24
>> ageString = datestr(ageInDays, 'HH:MM:SS.FFF')
ageString =
    '00:23:24.068'
>> ageInSecs = newFig.Age
ageInSecs =
       1404.06771035492
</pre>
<p>Note that an alternative way to set the computed property <b>Age</b> would have been to set its value to be an anonymous function, but this would have necessitated invoking it with parenthesis (as in: <code>ageInSecs = newFig.Age()</code>). By setting the property&#8217;s <b>GetMethod</b> meta-property we avoid this need.<br />
Keen readers will have noticed that the mechanism that I outlined above for the <b>Age</b> property/method can also be used to add custom user methods. For example, we can create a new custom property named <b>refresh</b> that would be read-only and have a <b>GetMethod</b> which is the function handle of the function that refreshes the object in some way.<br />
Do you have any special uses for custom user-defined properties/methods in your program? or perhaps you have a use-case that might show MathWorks why sub-classing the built-in classes might improve your work? if so, then please place a comment about it below. If enough users show MathWorks why this is important, then maybe it will be fixed in some future release.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects">Adding custom properties to GUI objects</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Adding dynamic properties to graphic handles</title>
		<link>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-dynamic-properties-to-graphic-handles</link>
					<comments>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 16 Sep 2015 17:26:44 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6006</guid>

					<description><![CDATA[<p>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles">Adding dynamic properties to graphic handles</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" rel="bookmark" title="Adding custom properties to GUI objects">Adding custom properties to GUI objects </a> <small>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A client recently asked me to extend one of Matlab&#8217;s built-in graphic containers (<a target="_blank" href="/articles/matlab-layout-managers-uicontainer-and-relatives"><i><b>uiflowcontainer</b></i></a> in this specific case) with automatic scrollbars that would enable the container to act as a scroll-panel. The basic idea would be to dynamically monitor the container&#8217;s contents and when it is determined that they overflow the container&#8217;s boundaries, then attach horizontal/vertical scrollbars to enable scrolling the contents into view:<br />
<center><figure style="width: 350px" class="wp-caption aligncenter"><img decoding="async" alt="Scrollable Matlab container" src="https://undocumentedmatlab.com/images/uiflowcontainer_scroll.gif" title="Scrollable Matlab container" width="350" height="260" /><figcaption class="wp-caption-text">Scrollable Matlab container</figcaption></figure></center><br />
This may sound simple, but there are actually quite a few undocumented hacks that make this possible, including listening to <code>ObjectChildAdded/ObjectChildRemoved</code> events, location/size/visibility events, layout changes etc. Maybe I&#8217;ll blog about it in some future article.<br />
Today&#8217;s post is focused on a specific aspect of this project, attaching dynamic properties to the builtin <i><b>uiflowcontainer</b></i>, that would enable users to modify the container&#8217;s properties directly, as well as control aspects of the scrolling using the new properties: handles to the parent container, as well as the horizontal and vertical scrollbars, and even a new <i>refresh()</i> method.<br />
<span id="more-6006"></span><br />
The &#8220;textbook&#8221; approach to this would naturally be to create a new class that extends (inherits) <i><b>uiflowcontainer</b></i> and includes these new properties and methods. Unfortunately, for some reason that escapes my understanding, MathWorks saw fit to make all of its end-use graphic object classes <code>Sealed</code>, such that they cannot be extended by users. I did ask for this to be changed long ago, but the powers that be apparently decided that it&#8217;s better this way.<br />
So the fallback would be to create our own dedicated class having all the new properties as well as those of the original container, and ensure that all the property values are synchronized in both directions. This is probably achievable, if you have a spare few days and a masochistic state of mind. Being the lazy bum and authority-rebel that I am, I decided to take an alternate approach that would simply add my new properties to the built-in container handle. The secret lies in the undocumented function <i><b>schema.prop</b></i> (for HG1, R2014a and older) and the fully-documented <i><b>addprop</b></i> function (for HG2, R2014b and newer).<br />
In the examples below I use a panel, but this mechanism works equally well on any Matlab HG object: axes, lines, uicontrols, figures, etc.</p>
<h3 id="HG2">HG2 &#8211; addprop function</h3>
<p>The <i><b>addprop</b></i> function is actually a public method of the <code>dynamicprops</code> class. Both the <code>dynamicprops</code> class as well as its <i><b>addprop</b></i> function are <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/dynamicprops.addprop.html">fully documented</a>. What is NOT documented, as far as I could tell, is that all of Matlab&#8217;s builtin handle graphics objects indirectly inherit <code>dynamicprops</code>, via <code>matlab.graphics.Graphics</code>, which is a high-level superclass for all HG objects. The bottom line is that we can dynamically add run-time properties to any HG object, without affecting any other object. In other words, the new properties will only be added to the handles that we specifically request, and not to any others. This suits me just fine:</p>
<pre lang='matlab'>
hProp = addprop(hPanel, 'hHorizontalScrollBar');
hPanel.hHorizontalScrollBar = hMyScrollbar;
hProp.SetAccess = 'private';  % make this property read-only
</pre>
<p>The new property <code>hHorizontalScrollBar</code> is now added to the <code>hPanel</code> handle, and can be accessed just like any other read-only property. For example:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">get</span><span style="color: #080;">(</span>hPanel, <span style="color:#A020F0;">'hHorizontalScrollBar'</span><span style="color: #080;">)</span>
<span style="color: #0000FF;">ans</span> =
    JavaWrapper
&gt;&gt; hPanel.<span style="">hHorizontalScrollBar</span>
<span style="color: #0000FF;">ans</span> =
    JavaWrapper
&gt;&gt; hPanel.<span style="">hHorizontalScrollBar</span> = <span style="color: #33f;">123</span>
<span style="color: #FF0000;">You cannot set the read-only property 'hHorizontalScrollBar' of UIFlowContainer.</span></pre>
</div>
</div>
<p>Adding new methods is more tricky, since we do not have a corresponding <i>addmethod</i> function. The trick I used was to create a new property having the requested new method&#8217;s name, and set its read-only value to a handle of the requested function. For example:</p>
<pre lang='matlab'>
hProp = addprop(hPanel, 'refresh');
hPanel.refresh = @myRefreshFunc;
hProp.SetAccess = 'private';  % make this property read-only
</pre>
<p>We can then invoke the new <i>refresh</i> &#8220;method&#8221; using the familiar dot-notation:</p>
<pre lang='matlab'>hPanel.refresh();</pre>
<p>Note: if you ever need to modify the initial value in your code, you should revert the property&#8217;s <b>SetAccess</b> meta-property to <code>'public'</code> before Matlab will enable you to modify the value:</p>
<pre lang='matlab'>
try
    % This will raise an exception if the property already exists
    hProp = addprop(hPanel, propName);
catch
    % Property already exists - find it and set its access to public
    hProp = findprop(hPanel, propName);
    hProp.SetAccess = 'public';
end
hPanel.(propName) = newValue;
</pre>
<h3 id="HG1">HG1 &#8211; schema.prop function</h3>
<p>In HG1 (R2014a and earlier), we can use the undocumented <i><b>schema.prop</b></i> function to add a new property to any HG handle (which is a numeric value in HG1). Donn Shull <a target="_blank" href="/articles/udd-properties">wrote about <i><b>schema.prop</b></i></a> back in 2011, as part of his series of articles on UDD (Unified Data Dictionary, MCOS&#8217;s precursor). In fact, <i><b>schema.prop</b></i> is so useful that it has its own <a target="_blank" href="/articles/tag/schemaprop">blog tag here</a> and appears in no less than 15 separate articles (excluding today). With HG2&#8217;s debut 2 years ago, MathWorks tried very hard to rid the Matlab code corpus of all the legacy schema-based, replacing most major functionalities with MCOS-based HG2 code. But so far it has proven impossible to get rid of schema completely, and so schema code is still used extensively in Matlab to this day (R2015b). Search your Matlab path for &#8220;schema.prop&#8221; and see for yourself.<br />
Anyway, the basic syntax is this:</p>
<pre lang='matlab'>hProp = schema.prop(hPanel, propName, 'mxArray');</pre>
<p>The <code>'mxArray'</code> specifies that the new property can accept any data type. We can limit the property to only accept certain types of data by specifying a less-generic data type, among those recognized by UDD (<a target="_blank" href="/articles/udd-properties#DataType">details</a>).<br />
Note that the meta-properties of the returned <code>hProp</code> are somewhat different from those of HG2&#8217;s <code>hProp</code>. Taking this into account, here is a unified function that adds/updates a new property (with optional initial value) to any HG1/HG2 object:</p>
<pre lang='matlab'>
function addProp(hObject, propName, initialValue, isReadOnly)
    try
        hProp = addprop(hObject, propName);  % HG2
    catch
        try
            hProp = schema.prop(hObject, propName, 'mxArray');  % HG1
        catch
            hProp = findprop(hObject, propName);
        end
    end
    if nargin > 2
        try
            hProp.SetAccess = 'public';  % HG2
        catch
            hProp.AccessFlags.PublicSet = 'on';  % HG1
        end
        hObject.(propName) = initialValue;
    end
    if nargin > 3 && isReadOnly
        try
            % Set the property as read-only
            hProp.SetAccess = 'private';  % HG2
        catch
            hProp.AccessFlags.PublicSet = 'off';  % HG1
        end
    end
end
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles">Adding dynamic properties to graphic handles</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" rel="bookmark" title="Adding custom properties to GUI objects">Adding custom properties to GUI objects </a> <small>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Property value change listeners</title>
		<link>https://undocumentedmatlab.com/articles/property-value-change-listeners?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=property-value-change-listeners</link>
					<comments>https://undocumentedmatlab.com/articles/property-value-change-listeners#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Aug 2014 14:12:55 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4955</guid>

					<description><![CDATA[<p>HG handle property changes can be trapped in a user-defined callback. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/property-value-change-listeners">Property value change listeners</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2" rel="bookmark" title="copyobj behavior change in HG2">copyobj behavior change in HG2 </a> <small>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types" rel="bookmark" title="Setting class property types">Setting class property types </a> <small>Matlab's class properties have a simple and effective mechanism for setting their type....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>For performance reasons, it is almost always better to respond to events (<i>asynchronously</i>), than to continuously check a property value (<i>synchronous polling</i>). Therefore, if we wish to do something when some property value is changed (e.g., log the event, shut down the system, liquidate the portfolio, call the police, &#8230;), then it is preferable to attach a property-change listener callback.<br />
The standard (documented) way of attaching a value-change listener to Matlab class properties is via the <i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/handle.addlistener.html">addlistener</a></b></i> function. This only works for handle (not value) classes, and only to those properties that have the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/matlab_oop/listening-for-changes-to-property-values.html#brkimdj-1"><b>SetObservable</b> and/or <b>GetObservable</b> attribute turned on</a>:</p>
<pre lang='matlab'>addlistener(hClassObject, propertyName, 'PostSet', @myCallbackFcn);</pre>
<p>This is all nice and well for Matlab class properties, but what about HG (handle Graphics: plots &#038; GUI) properties? Can we similarly listen to changes in (say) the axes limits? Until now this has been possible, but undocumented. For example, this will trigger <i>myCallbackFcn(hAxes,eventData)</i> whenever the axes limits change (due to zoom, pan, plotting etc.):</p>
<pre lang='matlab'>
addlistener(gca, 'YLim', 'PostSet', @(hAxes,eventData) myCallbackFcn(hAxes,eventData));
% Or (shorter equivalent):
addlistener(gca, 'YLim', 'PostSet', @myCallbackFcn);
</pre>
<p>This could be very useful when such properties could be modified from numerous different locations. Rather than updating all these location to call the relevant callback function directly, we simply attach the callback to the property-change listener. It could also be useful in cases where for some reason we cannot modify the source of the update (e.g., third-party or legacy code).<br />
In addition to <code>PostSet</code>, we could also set listeners for <code>PreSet</code>. Also, we could set listeners on <code>PostGet</code> and <code>PreGet</code> &#8211; this could be useful for calculating dynamic (dependent) property values.<br />
<span id="more-4955"></span></p>
<h3 id="under-the-hood">Under the hood</h3>
<p>The HG1 variant of <i><b>addlistener</b></i> is basically equivalent to the following low-level UDD-based code snippet, as <a target="_blank" href="/articles/udd-events-and-listeners">explained here</a>:</p>
<pre lang='matlab'>
% Create the listener object
hAxes = handle(gca);  % a UDD axes class object
hProp = findprop(hAxes,'YLim');  % a schema.prop class object
hListener = handle.listener(hAxes, hProp, 'PropertyPostSet', @myCallbackFcn);
% persist the listener in memory for as long as the source object (hAxes) is alive
setappdata(hAxes, 'listener__', hListener);
</pre>
<p>(in old Matlab releases, <i><b>addlistener</b></i> was a regular m-function that placed the listeners in the source handle&#8217;s <b>ApplicationData</b> property, as the code above shows; newer releases reimplemented <i><b>addlistener</b></i> as an internal built-in function and the listener is now stored somewhere in the DLL&#8217;s inaccessible memory, rather than in the <b>ApplicationData</b> property)<br />
In HG2, <i><b>handle.listener</b></i> no longer works. Fortunately, we don&#8217;t need it since we have <i><b>addlistener</b></i> that works the same way for both HG1 (UDD objects) and HG2 (MCOS objects). Kudos on the backward-compatibility aspect, MathWorks!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/property-value-change-listeners">Property value change listeners</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2" rel="bookmark" title="copyobj behavior change in HG2">copyobj behavior change in HG2 </a> <small>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types" rel="bookmark" title="Setting class property types">Setting class property types </a> <small>Matlab's class properties have a simple and effective mechanism for setting their type....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/property-value-change-listeners/feed</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
		<item>
		<title>Draggable plot data-tips</title>
		<link>https://undocumentedmatlab.com/articles/draggable-plot-data-tips?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=draggable-plot-data-tips</link>
					<comments>https://undocumentedmatlab.com/articles/draggable-plot-data-tips#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 23 Oct 2013 22:01:32 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.class]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4294</guid>

					<description><![CDATA[<p>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips">Draggable plot data-tips</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-plot-brushed-data" rel="bookmark" title="Accessing plot brushed data">Accessing plot brushed data </a> <small>Plot data brushing can be accessed programmatically using very simple pure-Matlab code...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A couple of years ago, I was asked by a client to figure out a way to make Matlab plot data-tips movable. The problem was that he had a very crowded plot and Matlab&#8217;s standard data-tips are displayed immediately adjacent to the data, thereby overlapping the plot parts. Matlab&#8217;s standard data-tips enable dragging to a very limited extent (only to the 4 corners of the data-point), and in any case the displayed textbox remains directly attached to the data point.<br />
So I developed a small utility for my client that solves this problem. I then forgot all about it until a few days ago when I came across it again. Yesterday I uploaded this <i><b>draggableDataTips</b></i> utility to the File Exchange, where you can <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/44065-draggable-data-tips">download it</a>.<br />
<i><b>draggableDataTips</b></i> enables the user to interactively drag any newly-created data-tip, anywhere in the Matlab figure. A dashed line connects the dragged data-tip with the original data point. Simple, intuitive, and effective. At 300 lines, the <i>draggableDataTips.m</i> source code is compact and easy to follow, and you&#8217;re welcome to take a look and further customize this utility for your specific needs.<br />
<center><figure style="width: 451px" class="wp-caption aligncenter"><a target="_blank" href="/images/draggableDataTips.png"><img loading="lazy" decoding="async" alt="draggableDataTips utility in action" src="https://undocumentedmatlab.com/images/draggableDataTips.png" title="draggableDataTips utility in action" width="451" height="293" /></a><figcaption class="wp-caption-text"><i><b>draggableDataTips</b></i> utility in action</figcaption></figure></center><br />
<span id="more-4294"></span></p>
<h3 id="implementation">Technical implementation</h3>
<p>The implementation of <i><b>draggableDataTips</b></i> relies on undocumented aspects of the data-cursor object exposed via the <i><b>datacursormode</b></i> function. I have already shown how these can be used to <a target="_blank" href="/articles/controlling-plot-data-tips/">customize and control data-tips programmatically</a> (rather than interactively). For <i><b>draggableDataTips</b></i>, we first get the cursor object&#8217;s meta-data <i><b>classhandle</b></i> (a <i><b>schema.class</b></i> object), then use it to find the meta-data for its hidden <b>CurrentDataCursor</b> property (a <i><b>schema.prop</b></i> object). There is also a more direct approach, using the <i><b>findprop</b></i> function.<br />
Whichever alternative we choose, we finally use this object to set the property&#8217;s <b>SetFunction</b> meta-property. Quite straight-forward, I should say:</p>
<pre lang='matlab'>
% Get the cursor-mode object
cursorObj = datacursormode(hFig);
% Alternative #1: the indirect route to the meta-property
ch = classhandle(cursorObj);
hPropIdx = strcmpi(get(ch.Properties,'Name'), 'CurrentDataCursor');
hProp = ch.Properties(hPropIdx);
% Alternative #2: the direct approach
hProp = findprop(cursorObj, 'CurrentDataCursor');
% Update the meta-property to use a custom function whenever new data-tips are created
hProp.SetFunction = @installNewMoveFcn;
</pre>
<p>This has the effect that all new data-tips that will be created from then on will call our custom <i>installNewMoveFcn</i> function when the data-tip object is created. This <i>installNewMoveFcn</i> function, in turn, simply replaces the data-tips standard default callback for mouse movement (which is used while dragging), to a new custom function <i>textBoxUpdateFcn</i>:</p>
<pre lang='matlab'>
% Install a replacement callback function for datatip textbox mouse movement
function hDataTip = installNewMoveFcn(cursorObj, hDataTip)
    srcObjs = get(hDataTip.SelfListenerHandles,'SourceObject');
    for srcIdx = 1 : length(srcObjs)
        if strcmpi(srcObjs{srcIdx}.Name,'Orientation')
            hDataTip.SelfListenerHandles(srcIdx).Callback = @textBoxUpdateFcn;
            hDataTip.MarkerHandle.Marker = 'none';
            break;
        end
    end
end
</pre>
<p>The <i>textBoxUpdateFcn</i> function basically moves the datatip textbox to the new mouse location, without limiting its positions as Matlab&#8217;s standard default callback function did. A dashed connector line is then drawn to connect the center of the textbox with the data-point. It&#8217;s a bit long to include here, but interested readers are welcome to look at the code (lines #99 onward in <i>draggableDataTips.m</i>).<br />
As can be seen from the screenshot above, standard and draggable data-tips can be used in the same plot. This is done by simply turning the draggability functionality on and off by <i><b>draggableDataTips</b></i> before creating a new data-tip (using either alt-click or <a target="_blank" href="/articles/controlling-plot-data-tips/">programmatically</a>):</p>
<pre lang='matlab'>
draggableDataTips on    % or: draggableDataTips('on')  or: draggableDataTips(true)
draggableDataTips off   % or: draggableDataTips('off') or: draggableDataTips(false)
</pre>
<p>Notes:</p>
<ol>
<li>The actual code of <i><b>draggableDataTips</b></i> naturally contains more sanity checks, exception handling etc. I have only presented the core code in the snippets above, but you should always include such extra checks in any real-life program.</li>
<li>There is a minor bug that causes the connector line to be on top of the box rather than beneath it, but aside from this all works ok. For some reason, <i><b>uistack</b></i> did not work. If anyone has a fix for this bug, please let me know.</li>
<li>Did you notice that Java was not mentioned anywhere above? Mode managers, such as the data-cursor mode, use pure-Matlab functionality.</li>
</ol>
<h3 id="HG2">HG2</h3>
<p>Unfortunately, when I tested <i><b>draggableDataTips</b></i> on <a target="_blank" href="/articles/hg2-update/">HG2</a>, Matlab&#8217;s upcoming new graphics engine, the utility failed. Data-cursors have undergone a significant reengineering in HG2 (about time!), causing multiple properties and methods to change names and functionality. But this could be overcome (see lines #43-53 in <i>draggableDataTips.m</i>).<br />
However, I could not overcome the apparent fact that unlike HG1 (or more specifically, <i><b>schema</b></i> objects, that HG1 uses for its data-tips functionality), in HG2 (or rather, MCOS class objects) we cannot override an object&#8217;s meta-properties, specifically its <b>SetMethod</b> (which is the MCOS equivalent of <i><b>schema.prop</b></i>&#8216;s <b>SetFunction</b> meta-property).<br />
So for the moment, <i><b>draggableDataTips</b></i> does not work on HG2. I hope to find a solution for this by the time HG2 launches. If anyone finds a fix for the problem, please let me know. If I ever find or receive a fix, I will update this post with the relevant technical details.<br />
For the moment there is no rush, since HG2 is still relatively far away in the distant future, and <i><b>draggableDataTips</b></i> works splendidly in the current HG1.<br />
Have you used plot data-tips in some nifty way? If so, please share your experience in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips">Draggable plot data-tips</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-plot-brushed-data" rel="bookmark" title="Accessing plot brushed data">Accessing plot brushed data </a> <small>Plot data brushing can be accessed programmatically using very simple pure-Matlab code...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/draggable-plot-data-tips/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Setting class property types</title>
		<link>https://undocumentedmatlab.com/articles/setting-class-property-types?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setting-class-property-types</link>
					<comments>https://undocumentedmatlab.com/articles/setting-class-property-types#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 18 Apr 2013 14:12:06 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[MCOS]]></category>
		<category><![CDATA[Object oriented]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<category><![CDATA[UDD]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3725</guid>

					<description><![CDATA[<p>Matlab's class properties have a simple and effective mechanism for setting their type.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/setting-class-property-types">Setting class property types</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types-2" rel="bookmark" title="Setting class property types &#8211; take 2">Setting class property types &#8211; take 2 </a> <small>R2016a saw the addition of class property types. However, a better alternative has existed for many years. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>When I wrote about the <a target="_blank" href="/articles/undocumented-classdef-attributes/">undocumented aspects of classdef properties</a> half a year ago, I did not expect to learn of another major undocumented aspect in Matlab&#8217;s class-object system. last month I discovered the additional undocumented classdef Description and DetailedDescription attributes, and updated that article accordingly. But a few days ago I was pleasantly surprised to read Amro&#8217;s <a target="_blank" href="/articles/undocumented-classdef-attributes/#comment-189056">comment</a> about an entirely new and undocumented aspect of Matlab MCOS classes.</p>
<p><a target="_blank" rel="nofollow" href="http://stackoverflow.com/users/97160/amro">Amro</a> is a top contributor on StackOverflow, where he frequently answers questions before I even get any subscription notification about them&#8230; His answers are generally characterized by a deep technical understanding of Matlab, and I&#8217;ve learned quite a lot from him in the past few years. This time was no different.</p>
<p>In a nutshell, Amro found an undocumented way to specify a class object property&#8217;s type, in such a way that would prevent accidental setting to an incompatible value. For example, if we have a class with properties <b>Width</b> and <b>Height</b>, we probably want to restrict their possible values to numbers, to prevent setting a string or struct value.</p>
<p>In UDD classes, we can do this easily by setting the property&#8217;s <b>DataType</b> meta-property. An easy way to do this is by setting the second argument of the <a target="_blank" href="/articles/creating-a-simple-udd-class/"><i><b>schema.prop</b></i> function</a>. A detailed explanation was provided <a target="_blank" href="/articles/udd-properties/">here</a>.</p>
<p>We can still do this today, since UDD classes are still supported, side-by-side with the newer MCOS classes. Unfortunately, MCOS does not provide a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/matlab_oop/defining-properties.html">documented</a> way of specifying the property type as in UDD.</p>
<p>One simple way to prevent unintentional MCOS property updates is to <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/matlab_oop/implementing-a-set-get-interface-for-properties.html">override the property&#8217;s <i><b>set</b></i> method</a>. In fact, this was the <a target="_blank" rel="nofollow" href="http://stackoverflow.com/a/7192964/233829">solution</a> of Jonas, another StackOverflow heavyweight:</p>
<pre lang='matlab'>
classdef myClass
   properties
      myProperty = uint16(23); %# specify default value using correct type
   end
   methods
      function obj = set.myProperty(obj,val)
         if ~isa(val,'uint16')
            error('only uint16 values allowed')
         end
         %# assign the value
         obj.myProperty = val;
      end
   end
end
</pre>
<p>But it turns out that there&#8217;s a much cleaner and simpler solution, <a target="_blank" rel="nofollow" href="http://stackoverflow.com/a/15992558/233829">provided</a> by Amro:</p>
<pre lang='matlab'>
classdef Packet
    properties
        HeaderLength@uint16
        PayloadLength@uint16 = uint16(0);
        PacketType@char
    end
end
</pre>
<p><span id="more-3725"></span><br />
As Amro notes, if you try to set a property with the wrong type, you get an error:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; p = Packet;
&gt;&gt; p.<span style="">PacketType</span> = <span style="color:#A020F0;">'tcp'</span>;  <span style="color: #228B22;">% ok</span>
&gt;&gt; p.<span style="">HeaderLength</span> = <span style="color: #33f;">100</span>;  <span style="color: #228B22;">% not ok - should be a uint16</span>
<span style="color: #FF0000;">While setting the 'HeaderLength' property of Packet:
Value must be 'uint16'</span>.</pre>
</div>
</div>
<p>This syntax apparently supports all primitive types (<i><b>char, int32, double, struct, cell</b></i> etc.), in addition to any user-defined ones (just use any class name).<br />
Note that setting the type as above seems to override any <i><b>set</b></i> method that may have been specified for the property.</p>
<p>Amro came across this syntax in an internal class in R2013a (<i>toolboxdir(&#8216;matlab&#8217;)/graphics/+graphics/+internal/+figfile/@FigFile/FigFile.m</i>), but it also worked in R2012a, and probably older versions as well&#8230;</p>
<p>I admit there&#8217;s not much original work here by me &#8211; it&#8217;s basically all by Amro (and Donn Shull for the UDD part). But I thought it&#8217;s important enough to bring to the attention of the community.</p>
<p>I love to discover such undocumented treasures by digging in Matlab&#8217;s function. If you ever discover other such buried treasures, please do let me know by email or a comment.</p>
<hr />
<p><b><u>Addendum June 21, 2013</u></b>: As Sebastian Hölz mentioned in his <a href="/articles/setting-class-property-types/#comment-215669">comment</a> below, the general syntax appears to be:</p>
<pre lang='matlab'>
properties
   propName@className dimensionType = initialValue
end
</pre>
<p>where <code>className</code>, <code>dimensionType</code> and <code>initialValue</code> are optional elements:</p>
<ul>
<li><code>className</code> can be any Matlab class/type, such as <code>double</code>, <code>single</code>, or <code>UserClass</code></li>
<li><code>dimensionType</code> can be one of the following terms: <code>scalar</code>, <code>vector</code>, or <code>matrix</code></li>
<li>the property may also be initiated with an <code>initialValue</code> (otherwise it receives a default value, depending on the property class)</li>
</ul>
<hr />
<p><b><u>Addendum August 12, 2014</u></b>: In a related matter, we can limit the values that a property can accept using the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/simulink/slref/matlab.system.stringset-class.html">matlab.system.StringSet</a> class of the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/simulink/slref/matlab.system-class.html">matlab.System</a> package, as recently <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/138149-autocomplete-of-properties-for-hgsetget-derived-class#answer_144336">discovered</a> by Oleg Komarov (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/simulink/ug/limit-property-values-to-a-finite-set-of-strings-1.html">additional details</a>; <a target="_blank" href="/articles/class-object-tab-completion-and-improper-field-names">additional aspects of class property tab-completion</a>):</p>
<pre lang='matlab'>
classdef foo < matlab.System
    properties
        Coordinates
    end
    properties(Hidden,Transient)
        CoordinatesSet = matlab.system.StringSet({'north','south','east','west'});
    end
end
</pre>
<p><center><img loading="lazy" decoding="async" alt="restricting Matlab property values" src="https://www.mathworks.com/matlabcentral/answers/uploaded_files/15194/Capture.PNG" title="restricting Matlab property values" width="309" height="129"/></center></p>
<hr />
<p><b><u>Addendum April 8, 2015</u></b>: As reported by Martin A. <a target="_blank" href="/articles/plot-legend-title#comment-347508">here</a> and also <a target="_blank" href="/articles/setting-class-property-types#comment-343150">below</a>, R2015a has apparently added the new (and hidden) <em>Type</em> property to the <em>meta.property</em> class and the <em>InputTypes</em> and <em>OutputTypes</em> properties to the the <em>meta.method</em> class. This enables specifying and querying the types of properties as well as method inputs/outputs. For example:</p>
<pre lang="matlab">
mc = ?matlab.graphics.axis.Axes;
mc.PropertyList(1).Name % Camera
mc.PropertyList(1).Type % matlab.graphics.axis.camera.Camera
mc.MethodList(49).Name % addlistener
mc.MethodList(49).InputNames % [sources, propertyname, eventname, callback]
mc.MethodList(49).InputTypes % [handle, asciiString, char vector, function_handle scalar]
</pre>
<hr />
<p><b><u>Addendum November 11, 2015</u></b>: <a href="/articles/setting-class-property-types#comment-362420">Apparently</a>, when using the <code>@double</code> syntax, Matlab only allows the property to receive real values. In order to enable complex values, we can also add the undocumented "complex" attribute. Note that we have to enter the dimensionality (scalar/vector/matrix) first, since "complex" is not accepted as a valid dimensionality value. For example:</p>
<pre lang='matlab' highlight='4,11'>
% This is ok:
classdef foo
    properties
        bar@double scalar complex = 1 + 2i
    end
end
% This causes an error:
classdef foo
    properties
        bar@double complex = 1 + 2i
    end
end
</pre>
<hr />
<p><b><u>Addendum April 28, 2016</u></b>: Matlab R2016a now has a similar documented functionality. However, I feel that there are important drawbacks to the new functionality compared to the one presented here. Read the <a href="/articles/setting-class-property-types-2" target="_blank">full discussion about this</a>.<br />
The new (documented) syntax automatically type-casts the data to the specified data type, were possible, something that the undocumented (@) syntax presented above does not. In other words, the undocumented syntax is stricter and expects the data to be exactly the specified data type, without attempting any type-casting. As <a href="/articles/setting-class-property-types-2#comment-375230" target="_blank">reported by Martin Afanasjew</a>, we can add the <code>property</code> attribute to the data type to replicate the new syntax's automatic type-casting:</p>
<pre lang="matlab" highlight='4'>
classdef foo
    properties
        prop1@char = 'A'  % will only accept char inputs, not numeric values
        prop2@char property = 65  % will automatically type-cast: 65 will be converted to 'A'
    end
end
</pre>
<hr />
<p><b><u>Addendum September 30, 2022</u></b>: Matlab R2022a has made the legacy @ syntax unsupported, displaying an error message about it in the Matlab Editor, and generating a run-time error if you try to use a class that uses this syntax.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/setting-class-property-types">Setting class property types</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types-2" rel="bookmark" title="Setting class property types &#8211; take 2">Setting class property types &#8211; take 2 </a> <small>R2016a saw the addition of class property types. However, a better alternative has existed for many years. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/setting-class-property-types/feed</wfw:commentRss>
			<slash:comments>41</slash:comments>
		
		
			</item>
		<item>
		<title>Setting axes tick labels format</title>
		<link>https://undocumentedmatlab.com/articles/setting-axes-tick-labels-format?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setting-axes-tick-labels-format</link>
					<comments>https://undocumentedmatlab.com/articles/setting-axes-tick-labels-format#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 Apr 2012 18:00:17 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2856</guid>

					<description><![CDATA[<p>Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/setting-axes-tick-labels-format">Setting axes tick labels format</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/axes-looseinset-property" rel="bookmark" title="Axes LooseInset property">Axes LooseInset property </a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Have you ever tried to customize the way in which tick labels appear in Matlab plot axes?<br />
For example, setting the numerical precision of the labels, or adding some short descriptive text (for example, the units)? If you have, then I bet that you have encountered the following dilemma: Once we modify the tick labels (for discussion sake, let&#8217;s assume the Y axis, so this is done by updating the <b>YTickLabel</b> property), then the corresponding <b>YTickLabelMode</b> property changes from &#8216;auto&#8217; to &#8216;manual&#8217; and loses its relationship to the tick values (<b>YTick</b>). So, if we now zoom or pan the plot, our new labels remain unchanged although the tick values have changed, causing much panic and frustration&#8230; If we also set the tick values manually, this solves <i>that</i> problem but leaves us with another: now, when we zoom or pan, we no longer see any ticks or tick labels at all!<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_orig.png" alt="Original plot" title="Original plot" width="134" height="143" /> <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_1b.png" alt="Manual labels, auto ticks" title="Manual labels, auto ticks" width="134" height="143" /> <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_1c.png" alt="Manual labels, manual ticks" title="Manual labels, manual ticks" width="134" height="143" /><figcaption class="wp-caption-text">Original plot (left)<br />Manual labels, auto ticks (center)<br />Manual labels, manual ticks (right)</figcaption></figure></center><br />
Of course, we can always trap the zoom and pan callback functions to update the tick labels dynamically while keeping the tick values automatically. This will work for these cases, but we need to do it separately for zoom and pan. Also, if we modify the axes limits explicitly (via the corresponding <b>YLim</b> property) or indirectly (by modifying the displayed plot data), then the callbacks are not called and the labels are not updated.</p>
<h3 id="solution">The solution &#8211; using a property change listener</h3>
<p>A better way to solve this problem is to simply trap changes to the displayed tick values, and whenever these occur to call our dedicated function to update the labels according to the new tick values. This can be done by using UDD, or more precisely the <a target="_blank" href="/articles/udd-events-and-listeners/">ability to trap update events on any property</a> (in our case, <b>YTick</b>). Such a mechanism was already <a target="_blank" href="/articles/continuous-slider-callback/#Property_Listener">demonstrated here</a> in 2010, as one way to achieve continuous slider feedback. The idea is to use the built-in <i><b>handle.listener</b></i> function with the PropertyPostSet event, as follows:</p>
<pre lang='matlab'>
hhAxes = handle(hAxes);  % hAxes is the Matlab handle of our axes
hProp = findprop(hhAxes,'YTick');  % a schema.prop object
hListener = handle.listener(hhAxes, hProp, 'PropertyPostSet', @myCallbackFunction);
setappdata(hAxes, 'YTickListener', hListener);
</pre>
<p>Note that we have used <i><b>setappdata</b></i> to store the <code>hListener</code> handle in the axes. This ensures that the listener exists for exactly as long as the axes does. If we had not stored this listener handle somewhere, then Matlab would have immediately deleted the listener hook and our callback function would not have been called upon tick value updates. Forgetting to store listener handles is a common pitfall when using them. If you take a look at the <i><b>addlistener</b></i> function&#8217;s code, you will see that it also uses <i><b>setappdata</b></i> after creating the listener, for exactly this reason. Unfortunately, <i><b>addlistsner</b></i> cannot always be used, and I keep forgetting under which circumstances, so I generally use <i><b>handle.listener</b></i> directly as above: It&#8217;s simple enough to use that I find I never really need to use the simple <i><b>addlistener</b></i> wrapper, but you are welcome to try it yourself.<br />
That&#8217;s all there is to it: Whenever <b>YTick</b> changes its value(s), our callback function (<i>myCallbackFunction</i>) will automatically be called. It is quite simple to set up. While we cannot use TeX in tick labels yet (this will change in the upcoming <a target="_blank" href="/articles/matlab-hg2/">HG2</a>), using <i><b>sprintf</b></i> formatting does enable quite a bit of flexibility in formatting the labels. For example, let&#8217;s say I want my tick labels to have the format &#8216;%.1fV&#8217; (i.e., always one decimal, plus the Volts units):</p>
<pre lang='matlab'>
function myCallbackFunction(hProp,eventData)    %#ok - hProp is unused
   hAxes = eventData.AffectedObject;
   tickValues = get(hAxes,'YTick');
   newLabels = arrayfun(@(value)(sprintf('%.1fV',value)), tickValues, 'UniformOutput',false);
   set(hAxes, 'YTickLabel', newLabels);
end  % myCallbackFunction
</pre>
<p><center><figure style="width: 300px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_2a.png" alt="Manual labels, automatically updated" title="Manual labels, automatically updated" width="134" height="143" /> <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_2b.png" alt="Manual labels, automatically updated" title="Manual labels, automatically updated" width="134" height="143" /><figcaption class="wp-caption-text">Manual labels, automatically updated</figcaption></figure></center></p>
<h3 id="duplicates">Handling duplicate tick labels</h3>
<p>Of course, &#8216;%.1fV&#8217; may not be a good format when we zoom in to such a degree that the values differ by less than 0.1 &#8211; in this case all the labels will be the same. So let&#8217;s modify our callback function to add extra decimals until the labels become distinct:</p>
<pre lang='matlab'>
function myCallbackFunction(hProp,eventData)    %#ok - hProp is unused
   hAxes = eventData.AffectedObject;
   tickValues = get(hAxes,'YTick');
   %newLabels = arrayfun(@(value)(sprintf('%.1fV',value)), tickValues, 'UniformOutput',false);
   digits = 0;
   labelsOverlap = true;
   while labelsOverlap
      % Add another decimal digit to the format until the labels become distinct
      digits = digits + 1;
      format = sprintf('%%.%dfV',digits);
      newLabels = arrayfun(@(value)(sprintf(format,value)), tickValues, 'UniformOutput',false);
      labelsOverlap = (length(newLabels) > length(unique(newLabels)));
      % prevent endless loop if the tick values themselves are non-unique
      if labelsOverlap && max(diff(tickValues))< 16*eps
         break;
      end
   end
   set(hAxes, 'YTickLabel', newLabels);
end  % myCallbackFunction
</pre>
<p><center><figure style="width: 300px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_3a.png" alt="non-distinct labels" title="non-distinct labels" width="134" height="143" /> <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_3b.png" alt="distinct labels" title="distinct labels" width="134" height="143" /><figcaption class="wp-caption-text">Non-distinct labels &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; distinct labels</figcaption></figure></center></p>
<h3 id="ticklabelformat"><i>ticklabelformat</i></h3>
<p>Based on a file that I received from an anonymous reader a few years ago, I have prepared a utility called <i><b>ticklabelformat</b></i> that automates much of the set-up above. Feel free to <a target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/36254-ticklabelformat">download</a> this utility and modify it for your needs &#8211; it&#8217;s quite simple to read and follow. The usage syntax is as follows:</p>
<pre lang='matlab'>
ticklabelformat(gca,'y','%.6g V')  % sets y axis on current axes to display 6 significant digits
ticklabelformat(gca,'xy','%.2f')   % sets x & y axes on current axes to display 2 decimal digits
ticklabelformat(gca,'z',@myCbFcn)  % sets a function to update the Z tick labels on current axes
ticklabelformat(gca,'z',{@myCbFcn,extraData})  % sets an update function as above, with extra data
</pre>
<h3 id="hg2">Addendum for HG2 (R2014b or newer releases)</h3>
<p>As I&#8217;ve indicated in <a href="/articles/setting-axes-tick-labels-format#comment-339729">my comment response</a> below, in HG2 (R2014b or newer) we need to listen to the <a href="/articles/undocumented-hg2-graphics-events" target="_blank">HG object&#8217;s <code>MarkedClean</code> event</a>, rather than to a property change event.<br />
I&#8217;ve updated my ticklabelformat utility accordingly, so that it works with both HG1 (pre-R2014a) and HG2 (R2014b+). Use this utility as-is, and/or look within its source code for the implementation details.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/setting-axes-tick-labels-format">Setting axes tick labels format</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/axes-looseinset-property" rel="bookmark" title="Axes LooseInset property">Axes LooseInset property </a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/setting-axes-tick-labels-format/feed</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
			</item>
		<item>
		<title>getundoc &#8211; get undocumented object properties</title>
		<link>https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getundoc-get-undocumented-object-properties</link>
					<comments>https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 21 Sep 2011 19:00:16 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2437</guid>

					<description><![CDATA[<p>getundoc is a very simple utility that displays the hidden (undocumented) properties of a specified handle object.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties">getundoc &#8211; get undocumented object properties</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/displaying-hidden-handle-properties" rel="bookmark" title="Displaying hidden handle properties">Displaying hidden handle properties </a> <small>I present two ways of checking undocumented hidden properties in Matlab Handle Graphics (HG) handles...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-cursorbar-object" rel="bookmark" title="Undocumented cursorbar object">Undocumented cursorbar object </a> <small>Matlab's internal undocumented graphics.cursorbar object can be used to present dynamic data-tip cross-hairs...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-private-object-properties" rel="bookmark" title="Accessing private object properties">Accessing private object properties </a> <small>Private properties of Matlab class objects can be accessed (read and write) using some undocumented techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week, I <a target="_blank" href="/articles/controlling-plot-data-tips/#Properties">presented</a> the list of undocumented properties available in Matlab&#8217;s cursor mode and data-tip objects. Over the past two years, I had posted <a target="_blank" href="/articles/category/hidden-property/">quite a few other articles</a> on this website that used such undocumented properties. So today I will show exactly how such properties can be discovered.<br />
Hidden properties are object properties that for some reason or other MathWorks has decided not to expose to the general public. They can still be used by Matlab users, just like any other regular property. But if you use the built-in <i><b>get</b></i> and <i><b>set</b></i> functions to list the object&#8217;s properties, you will not find the hidden properties listed. You need to know the hidden properties&#8217; exact name in order to use them. Which is where today&#8217;s post can help, by showing you how to list these hidden properties. I <a target="_blank" href="/articles/displaying-hidden-handle-properties/">wrote about this</a> a couple of years ago, and today&#8217;s article will expand on that original post.<br />
Hidden properties are by their very nature undocumented and not officially supported. For this reason, you should take extra care when relying on them in your code. They could change functionality or even be removed without prior notice in any future Matlab release. Still, some of these properties enable very important functionality, as I have often shown on this website.</p>
<h3 id="HideUndocumented">HideUndocumented</h3>
<p>There are two distinct manners by which undocumented properties can be seen in Matlab. The simplest was <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/1183#2277">reported</a> by Hans Olsson all the way back in 1997, in one of the very earliest posts on the CSSM newsgroup (there is no earlier public report, as far as I could tell). Since then, this method was mentioned in about a dozen <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/search_results?dur=all&#038;page=1&#038;query=hideundocumented&#038;search=+Go+&#038;search_string=hideundocumented&#038;search_submit=cssm">other CSSM posts</a>.<br />
By setting the Matlab root (handle 0)&#8217;s <b>HideUndocumented</b> property to &#8216;off&#8217; (default=&#8217;on&#8217;), subsequent calls to the built-in <i><b>get</b></i> and <i><b>set</b></i> functions list the hidden properties in addition to the regular ones. Note that <b>HideUndocumented</b> is itself a hidden property, which is why Hans&#8217; post is so important &#8211; he presented us with the loose end that then enabled us to untangle the hidden properties in any other HG object.<br />
Here is a simple example, showing <b>HideUndocumented</b>&#8216;s effect on the root (handle 0) object handle itself (hidden properties are highlighted):</p>
<pre lang='matlab' highlight='45,52,56,61,68,71,79,85,90-91,93-98'>
% Display only regular properties
>> get(0)
	CallbackObject = []
	CommandWindowSize = [86 51]
	CurrentFigure = []
	Diary = off
	DiaryFile = diary
	Echo = off
	FixedWidthFontName = Courier New
	Format = longG
	FormatSpacing = compact
	Language = he_il
	MonitorPositions = [ (2 by 4) double array]
	More = off
	PointerLocation = [1084 590]
	RecursionLimit = [500]
	ScreenDepth = [32]
	ScreenPixelsPerInch = [96]
	ScreenSize = [1 1 1440 900]
	ShowHiddenHandles = off
	Units = pixels
	BeingDeleted = off
	ButtonDownFcn =
	Children = []
	Clipping = on
	CreateFcn =
	DeleteFcn =
	BusyAction = queue
	HandleVisibility = on
	HitTest = on
	Interruptible = on
	Parent = []
	Selected = off
	SelectionHighlight = on
	Tag =
	Type = root
	UIContextMenu = []
	UserData = []
	Visible = on
% Display ALL properties (including hidden ones, which are highlighted below)
>> set(0,'HideUndocumented','off')
>> get(0)
	BlackAndWhite = off
	CallbackObject = []
	CommandWindowSize = [86 51]
	CurrentFigure = []
	Diary = off
	DiaryFile = diary
	Echo = off
	ErrorMessage = [ (1 by 79) char array]
	FixedWidthFontName = Courier New
	Format = longG
	FormatSpacing = compact
	HideUndocumented = off
	Language = he_il
	MonitorPositions = [ (2 by 4) double array]
	More = off
	PointerLocation = [1022 82]
	PointerWindow = [0]
	RecursionLimit = [500]
	ScreenDepth = [32]
	ScreenPixelsPerInch = [96]
	ScreenSize = [1 1 1440 900]
	ShowHiddenHandles = off
	Units = pixels
	AutomaticFileUpdates = on
	BeingDeleted = off
	PixelBounds = [0 0 0 0]
	ButtonDownFcn =
	Children = []
	Clipping = on
	CreateFcn =
	DeleteFcn =
	BusyAction = queue
	HandleVisibility = on
	HelpTopicKey =
	HitTest = on
	Interruptible = on
	Parent = []
	Selected = off
	SelectionHighlight = on
	Serializable = on
	Tag =
	Type = root
	UIContextMenu = []
	UserData = []
	ApplicationData = [ (1 by 1) struct array]
	Behavior = [ (1 by 1) struct array]
	Visible = on
	XLimInclude = on
	YLimInclude = on
	ZLimInclude = on
	CLimInclude = on
	ALimInclude = on
	IncludeRenderer = on
</pre>
<h3 id="schema">Property definitions</h3>
<p>An entirely different mechanism uses the <i><b>schema.prop</b></i> definitions that were <a target="_blank" href="/articles/udd-properties/">presented here</a> by Donn Scull at the beginning of 2011. The idea is to get the object&#8217;s <i><b>classhandle</b></i> reference, from it to get the list of properties definitions, and for each property look at its <b>Visible</b> meta-property: hidden properties will simply have <b>Visible</b>=&#8217;off&#8217;, whereas regular properties will have &#8216;on&#8217;.<br />
It turns out that there is not always a full correspondence between these two mechanism. I can&#8217;t remember specific examples, and perhaps these were fixed in the latest Matlab releases. It doesn&#8217;t matter, because merging the list of hidden properties reported by these two methods is always safe to do. Which is exactly what my <i><b>getundoc</b></i> utility does:</p>
<h3 id="getundoc">getundoc utility</h3>
<p>The <i><b>getundoc</b></i> utility is based on another utility by the same name, posted by <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/31831">Duane Hanselman</a> to the Matlab File Exchange in 2006 (Duane has elected to remove all his submissions from FEX a year or two ago, but that&#8217;s an entirely separate [and extremely heated] topic for a different discussion). Duane&#8217;s original <i><b>getundoc</b></i> utility relied only on the first (<b>HideUndocumented</b>) mechanism.<br />
I have since expanded this utility to include support for the second mechanism, as well as support for the upcoming HG2 (see below). The updated <i><b>getundoc</b></i> is now <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/32934-getundoc-get-undocumented-object-properties">available for download</a> on the File Exchange. Since it&#8217;s a very short utility, I will digress from my norm and simply present its code, in its present form, here:</p>
<pre lang='matlab'>
function c = getundoc(arg)
%GETUNDOC Get Undocumented Object Properties.
% GETUNDOC('OBJECT') or GETUNDOC(H) returns a structure of
% undocumented properties (names & values) for the object having handle
% H or indentified by the string 'OBJECT'.
%
% For example, GETUNDOC('axes') or GETUNDOC(gca) returns undocumented
% property names and values for the axes object.
% Extension of Duane Hanselman's original utility (which is no longer
% available on the File Exchange):
% D.C. Hanselman, University of Maine, Orono, ME 04469
% MasteringMatlab@yahoo.com
% Mastering MATLAB 7
% 2006-01-06
if nargin~=1
   error('One Input Required.')
end
if ischar(arg) % GETUNDOC('OBJECT')
   switch lower(arg)
   case 'root'                                                       % root
      h=0;
      hf=0;
   case 'figure'                                                   % figure
      h=figure('Visible','off');
      hf=h;
   otherwise                          % some other string name of an object
      hf=figure('Visible','off');
      object=str2func(arg);
      try
         h=object('Parent',hf,'Visible','off');
      catch
         error('Unknown Object Type String Provided.')
      end
   end
elseif ishandle(arg) % GETUNDOC(H)
   h=arg;
   hf=0;
else
   error('Unknown Object Handle Provided.')
end
wstate=warning;
warning off                                      % supress warnings about obsolete properties
try set(0,'HideUndocumented','off'); catch; end  % Fails in HG2
undocfnames=fieldnames(get(h));                  % get props including undocumented
try set(0,'HideUndocumented','on'); catch; end   % Fails in HG2
docfnames=fieldnames(get(h));                    % get props excluding undocumented
% Yair 18/3/2010 - add a few more undocs:
try
    % This works in HG1
    props = get(classhandle(handle(h)),'properties');
    undocfnames = [undocfnames; get(props(strcmp(get(props,'Visible'),'off')),'Name')];
catch
    % Yair 18/9/2011: In HG2, the above fails, so use the following workaround:
    try
        prop = findprop(handle(h),undocfnames{1});
        props = prop.DefiningClass.PropertyList;
        undocfnames = [undocfnames; {props.Name}'];   % {props([props.Hidden]).Name}
    catch
        % ignore...
    end
end
c = setdiff(undocfnames,docfnames);      % extract undocumented
% Get the values in struct format, if relevant
if ~isempty(c)
  s = struct;
  for fieldIdx = 1 : length(c)
      try
          fieldName = c{fieldIdx};
          s.(fieldName) = get(h,fieldName);
      catch
          s.(fieldName) = '???';
      end
  end
  c = s;
end
% Yair end
if hf~=0                     % delete hidden figure holding selected object
   delete(hf)
end
warning(wstate)
</pre>
<p>Usage of this utility is extremely simple:</p>
<pre lang='matlab'>
>> getundoc(0)
ans =
             ALimInclude: 'on'
         ApplicationData: [1x1 struct]
    AutomaticFileUpdates: 'on'
                Behavior: [1x1 struct]
           BlackAndWhite: 'off'
             CLimInclude: 'on'
            ErrorMessage: [1x79 char]
            HelpTopicKey: ''
        HideUndocumented: 'on'
         IncludeRenderer: 'on'
             PixelBounds: [0 0 0 0]
           PointerWindow: 0
            Serializable: 'on'
             XLimInclude: 'on'
             YLimInclude: 'on'
             ZLimInclude: 'on'
>> getundoc(gcf)
ans =
               ALimInclude: 'on'
    ActivePositionProperty: 'position'
           ApplicationData: [1x1 struct]
              BackingStore: 'on'
                  Behavior: [1x1 struct]
               CLimInclude: 'on'
                CurrentKey: ''
           CurrentModifier: {1x0 cell}
                 Dithermap: [64x3 double]
             DithermapMode: 'manual'
              DoubleBuffer: 'on'
            ExportTemplate: []
               FixedColors: [3x3 double]
                   HelpFcn: ''
              HelpTopicKey: ''
              HelpTopicMap: ''
           IncludeRenderer: 'on'
                 JavaFrame: [1x1 com.mathworks.hg.peer.HG1FigurePeer]
               MinColormap: 64
             OuterPosition: [436 374 568 502]
               PixelBounds: [0 0 560 420]
             PrintTemplate: []
              Serializable: 'on'
                    UseHG2: 'off'
                WaitStatus: []
               XLimInclude: 'on'
               YLimInclude: 'on'
               ZLimInclude: 'on'
</pre>
<h3 id="HG2">Fixes for HG2</h3>
<p>Unfortunately, in the new <a target="_blank" href="/articles/matlab-hg2/">HG2</a> (which is still not in production, but we must be prepared, mustn&#8217;t we?), the original mechanism above (<b>HideUndocumented</b>) fails completely (there is no such property in the new <code>matlab.ui.root</code> object), whereas the second mechanism (UDD property defs) needs to be modified: Apparently, <i><b>classhandle</b></i> fails for HG2 object handles. Instead, we use the workaround of using <i><b>findprop</b></i> to get the property definition for any regular property, then get its parent (the requested class definition), and then down again to list all available properties. Note that in HG2, the relevant meta-property is <b>Hidden</b> which holds logical (<b><i>true/false</i></b>) values, as opposed to <b>Visible</b> and &#8216;off&#8217;/&#8217;on&#8217; values for HG1 above.<br />
All of these fixes are now incorporated in the <i><b>getundoc</b></i> code that is listed above.<br />
When comparing the list of hidden properties in the existing HG1 and the new HG2, we see many interesting differences. And yes: the figure&#8217;s <a target="_blank" href="/articles/minimize-maximize-figure-window/#JavaFrame"><b>JavaFrame</b></a> property was indeed removed in HG2. Bummer! (don&#8217;t worry &#8211; there are several workarounds up my sleeve&#8230;)<br />
Do you have any favorite hidden property that you use in your code? If so, please tell us about it in a comment <a href="/articles/getundoc-get-undocumented-object-properties/#respond">below</a>.<br />
p.s. &#8211; For all the numerous good people telling me about <a target="_blank" href="/articles/cprintf-display-formatted-color-text-in-command-window/"><i><b>cprintf</b></i></a> &#8211; Yes: I am aware that the latest R2011b release has broken <i><b>cprintf</b></i>&#8216;s functionality. I plan to release a workaround sometime soon, when I have some spare time. I&#8217;ll keep everybody posted of course. Please be patient. (if you can&#8217;t wait, you can always <a target="_blank" href="/consulting/">hire me</a> to fix it sooner; otherwise I need to give priority to my paying clients&#8230;)</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties">getundoc &#8211; get undocumented object properties</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/displaying-hidden-handle-properties" rel="bookmark" title="Displaying hidden handle properties">Displaying hidden handle properties </a> <small>I present two ways of checking undocumented hidden properties in Matlab Handle Graphics (HG) handles...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-cursorbar-object" rel="bookmark" title="Undocumented cursorbar object">Undocumented cursorbar object </a> <small>Matlab's internal undocumented graphics.cursorbar object can be used to present dynamic data-tip cross-hairs...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-private-object-properties" rel="bookmark" title="Accessing private object properties">Accessing private object properties </a> <small>Private properties of Matlab class objects can be accessed (read and write) using some undocumented techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>UDD Events and Listeners</title>
		<link>https://undocumentedmatlab.com/articles/udd-events-and-listeners?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=udd-events-and-listeners</link>
					<comments>https://undocumentedmatlab.com/articles/udd-events-and-listeners#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 16 Mar 2011 18:43:16 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2200</guid>

					<description><![CDATA[<p>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/udd-events-and-listeners">UDD Events and Listeners</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events" rel="bookmark" title="Waiting for asynchronous events">Waiting for asynchronous events </a> <small>The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/capturing-print-events" rel="bookmark" title="Capturing print events">Capturing print events </a> <small>Matlab print events can be trapped by users to enable easy printout customization. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Donn Shull continues his exploration of the undocumented UDD mechanism, today discussing the important and extremely useful topic of UDD events</i></p>
<h3 id="model">The UDD event model</h3>
<p>The UDD event model is very similar to the MCOS event model. There is an excellent <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_oop/bqvggvt.html">discussion</a> of the MCOS event model in Matlab&#8217;s official documentation. Most of the MCOS information also applies to UDD if you make the following substitutions:</p>
<table>
<tbody>
<tr>
<th bgcolor="#D0D0D0">MCOS Event Model</th>
<th bgcolor="#D0D0D0">UDD Event Model</th>
</tr>
<tr>
<td bgcolor="#E7E7E7">notify</td>
<td bgcolor="#E7E7E7">send</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">event.EventData</td>
<td bgcolor="#E7E7E7">handle.EventData</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">events block</td>
<td bgcolor="#E7E7E7">schema.event</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">event.listener</td>
<td bgcolor="#E7E7E7">handle.listener</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">PreGet, PreSet</td>
<td bgcolor="#E7E7E7">PropertyPreGet, PropertPreSet</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">PostGet, PostSet</td>
<td bgcolor="#E7E7E7">PropertyPostGet, PropertyPostSet</td>
</tr>
</tbody>
</table>
<h3 id="handler">Event handler functions</h3>
<p>To begin the UDD event model discussion we will start at the end, with the event handler. The event handler function requires at least two input arguments: the source object which triggered the event, and an object of type <code>handle.EventData</code> or a subclass of <code>handle.EventData</code>.<br />
To demonstrate how this works, let&#8217;s write a simple event handler function. This event handler will display the class of the source event and the class of the event data:</p>
<pre lang="matlab">
function displayEventInfo(source, eventData)
%DISPLAYEVENTINFO display the classes of source, data objects
%
%   DISPLAYEVENTINFO(SOURCE, EVENTDATA) returns the classes
%   of the source object and the event data object
%
%   INPUTS:
%       SOURCE    : the event source
%       EVENTDATA : the event data
  if ~isempty(source)
    fprintf(1, 'The source object class is: %s',class(source));
  end
  if ~isempty(eventData)
    fprintf(1, 'The event data class is: %s',class(eventData));
  end
end
</pre>
<h3 id="listener">Creating a listener</h3>
<p>In the section on <a target="_blank" href="/articles/creating-a-simple-udd-class/">Creating a Simple UDD Class</a> we used <code>schema.event</code> in our <code>simple.object</code> class definition file to create a <code>simpleEvent</code> event. We now create an instance of <code>simple.object</code>, then use <b><i>handle.listener</i></b> to wait (&#8220;listen&#8221;) for the <code>simpleEvent</code> event to occur and call the <i>displayEventInfo</i> event handler function:</p>
<pre lang="matlab">
a = simple.object('a', 1);
hListener = handle.listener(a,'simpleEvent',@displayEventInfo);
setappdata(a, 'listeners', hListener);
</pre>
<p><b><u>Important:</u></b> The <code>hListener</code> handle must remain stored somewhere in Matlab memory, or the listener will not be used. For this reason, it is good practice to attach the listener handle to the listened object, using the <i><b>setappdata</b></i> function, as was done above. The listener will then be alive for exactly as long as its target object is alive.</p>
<h3 id="EventData">Creating an EventData object</h3>
<p>Next, create the <code>handle.EventData</code> object. The <code>handle.EventData</code> object constructor requires two arguments: an instance of the events source object, and the name of the event:</p>
<pre lang="matlab">evtData = handle.EventData(a, 'simpleEvent')</pre>
<h3 id="event">Generating an event</h3>
<p>The last step is actually triggering an event. This is done by issuing the <i><b>send</b></i> command for the specified object, event name and event data:</p>
<pre lang="matlab">
>> a.send('simpleEvent', evtData)
The source object class is: simple.object
The event data class is: handle.EventData
</pre>
<p>If there is other information that you wish to pass to the callback function you can create a subclass of the <code>handle.EventData</code>. Add properties to hold your additional information and use your subclass as the second argument of the <i><b>send</b></i> method.</p>
<h3 id="builtin">Builtin UDD events</h3>
<p>The builtin <code>handle</code> package has six event data classes which are subclasses of the base <code>handle.EventData</code> class. Each of these classes is paired with specific UDD events that Matlab generates. Actions that trigger these events include creating/destroying an object, adding/removing objects from a hierarchy, and getting/setting property values. The following table lists the event names and <code>handle.*EventData</code> data types returned for these events:</p>
<table>
<tbody>
<tr>
<th bgcolor="#D0D0D0">event data type</th>
<th bgcolor="#D0D0D0">event trigger</th>
</tr>
<tr>
<td bgcolor="#E7E7E7">handle.ClassEventData</td>
<td bgcolor="#E7E7E7">ClassInstanceCreated</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">handle.EventData</td>
<td bgcolor="#E7E7E7">ObjectBeingDestroyed</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">handle.ChildEventData</td>
<td bgcolor="#E7E7E7">ObjectChildAdded, ObjectChildRemoved</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">handle.ParentEventData</td>
<td bgcolor="#E7E7E7">ObjectParentChanged</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">handle.PropertyEventData</td>
<td bgcolor="#E7E7E7">PropertyPreGet, PropertyPostGet</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">handle.PropertySetEventData</td>
<td bgcolor="#E7E7E7">PropertyPreSet, PropertyPostSet</td>
</tr>
</tbody>
</table>
<p>As an example of some of these events let&#8217;s look at a <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/303232">question</a> recently asked on the CSSM newsgroup. The basic idea is that we want to monitor an axis, automatically make any added lines to be green in color, and prevent patches from being added.<br />
The solution is to monitor the <code>ObjectChildAdded</code> event for an axis. We will write an event handler which checks the <code>handle.ChildEventData</code> to see what type of child was added. In the case of lines we will set their color to green; patch objects will be deleted from the axis. Here is our event handler function:</p>
<pre lang="matlab">
function modifyAxesChildren(~, eventData)
%MODIFYAXESCHILDREN monitor and axis and modify added children
%
%   MODIFYAXESCHILDREN(SOURCE,EVENTDATA) is an event handler to
%   change newly-added lines to green and remove added patches
%
%   INPUTS:
%       EVENTDATA : handle.ChildEventData object
   switch eventData.Child.classhandle.Name
      case 'line'
         eventData.Child.set('Color', 'green');
         disp('Color changed to green.')
      case 'patch'
         eventData.Child.delete;
         disp('Patch removed.')
   end
end
</pre>
<p>Next create an axis, and a listener which is triggered when children are added:</p>
<pre lang="matlab">
% create a new axes and get its handle
a = hg.axes;
% create the listener
listen = handle.listener(a, 'ObjectChildAdded', @modifyAxesChildren);
% add a line
>> hg.line;
Color changed to green.
% try to add a patch
>> hg.patch;
Patch removed.
</pre>
<p>Removing a child with either the <i>delete</i> or the <i>disconnect</i> method generates an <code>ObjectChildRemoved</code> event. The <i>delete</i> method also generates the <code>ObjectBeingDestroyed</code> event. Changing a child&#8217;s parent with the <i>up</i> method generates an <code>ObjectParentChanged</code> event.<br />
Reading an object&#8217;s properties with either dot notation or with the <i>get</i> method generates <code>PropertyPreGet</code> and <code>PropertyPostGet</code> events.<br />
Changing the value of a property generates the <code>PropertyPreSet</code> and <code>PropertyPostSet</code> events. As we saw in the section on <a target="_Blank" href="/articles/udd-properties/">UDD properties</a>, when the <b>AbortSet</b> access flag is &#8216;on&#8217;, property set events are only generated when a <i><b>set</b></i> operation actually changes the value of the property (as opposed to leaving it unchanged).<br />
Note that the <b><i>handle.listener</i></b> syntax is slightly different for property events:</p>
<pre lang="matlab">
hProp = findprop(a, 'Value');
hListener = handle.listener(a,hProp,'PropertyPreGet',@displayEventInfo);
</pre>
<h3 id="Java">Java events</h3>
<p>The final specialized event data object in the handle package is <code>handle.JavaEventData</code>. In Matlab, Java classes are not UDD classes, but each Java instance can have a UDD <i>peer</i>. The peer is created using the <i><b>handle</b></i> function. The Java peers are created in either UDD&#8217;s <code>javahandle</code> package or the <code>javahandle_withcallbacks</code> package. As their names imply, the latter enables listening to Java-triggered events using a Matlab callback.<br />
To illustrate how this works we will create a Java Swing <code>JFrame</code> and listen for <code>MouseClicked</code> events:</p>
<pre lang="matlab">
% Create the Java Frame
javaFrame = javax.swing.JFrame;
javaFrame.setSize(200, 200);
javaFrame.show;
% Create a UDD peer for the new JFrame (two alternatives)
javaFramePeer = javaFrame.handle('CallbackProperties');  % alternative #1
javaFramePeer = handle(javaFrame, 'CallbackProperties');  % alternative #2
% Create the a listener for the Java MouseClicked event
listen = handle.listener(javaFramePeer, 'MouseClicked', @displayEventInfo);
</pre>
<p><center><figure style="width: 200px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="a simple Java Swing JFrame" src="https://undocumentedmatlab.com/images/UDD_Java_Frame.png" title="a simple Java Swing JFrame" width="200" height="200" /><figcaption class="wp-caption-text">a simple Java Swing JFrame</figcaption></figure></center><br />
When we click on the JFrame, our UDD peer triggers the callback:</p>
<pre lang="java">
The source object class is: javahandle_withcallbacks.javax.swing.JFrame
The event data class is: handle.JavaEventData
</pre>
<p>Since we created our peer in the <code>javahandle_withcallbacks</code> package, it is not necessary to create a listener using <i><b>handle.listener</b></i>. If we place our callback function handle in the <b>MouseClickedCallback</b> property it will be executed whenever the <code>MouseClicked</code> event is triggered. Such <b>*Callback</b> properties are automatically generated by Matlab when it creates the UDD peer (<a target="_blank" href="/articles/matlab-callbacks-for-java-events/">details</a>).</p>
<pre lang="matlab">
clear listen
javaFramePeer.MouseClickedCallback = @displayEventInfo
</pre>
<p>This will work the same as before without the need to create and maintain a <b><i>handle.listener</i></b> object. If we had created our UDD peer in the <code>javahandle</code> package rather than <code>javahandle_withcallbacks</code>, we would not have the convenience of the <b>MouseClickedCallback</b> property, but we could still use the <b><i>handle.listener</i></b> mechanism to monitor events.</p>
<h3 id="custom">Creating callback properties for custom UDD classes</h3>
<p>It is easy to add callback properties to user created UDD objects. The technique involves embedding a <code>handle.listener</code> object in the UDD object. To illustrate this, we add a <b>SimpleEventCallback</b> property to our <code>simple.object</code>, then use a <b>SimpleEventListener</b> property to hold our embedded <b><i>handle.listener</i></b>. Add the following to <code>simple.object</code>&#8216;s schema.m definition file:</p>
<pre lang="matlab">
   % Property to hold our callback handle
   prop = schema.prop(simpleClass, 'SimpleEventCallback', 'MATLAB callback');
   prop.setFunction = @setValue;
   % hidden property to hold the listener for our callback
   prop = schema.prop(simpleClass, 'SimpleEventListener', 'handle');
   prop.Visible = 'off';
end
function propVal = setValue(self, value)
   %SETVALUE function to transfer function handle from callback property to listener
   self.SimpleEventListener.Callback = value;
   propVal = value;
end
</pre>
<p>Next we add the following to our simple.object constructor file:</p>
<pre lang="matlab">
% set the hidden listener property to a handle.listener
simpleObject.SimpleEventListener = handle.listener(simpleObject, 'simpleEvent', []);
</pre>
<p>Now if we set the <b>SimpleObjectCallback</b> property to a function handle, the handle is transferred to the embedded <b><i>handle.listener</i></b> Callback property. When a <code>simpleEvent</code> event is generated, our <code>SimpleEventCallback</code> function will be executed.<br />
This series will conclude next week with a look at the special relationship between UDD and Java.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/udd-events-and-listeners">UDD Events and Listeners</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events" rel="bookmark" title="Waiting for asynchronous events">Waiting for asynchronous events </a> <small>The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/capturing-print-events" rel="bookmark" title="Capturing print events">Capturing print events </a> <small>Matlab print events can be trapped by users to enable easy printout customization. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/udd-events-and-listeners/feed</wfw:commentRss>
			<slash:comments>32</slash:comments>
		
		
			</item>
		<item>
		<title>UDD Properties</title>
		<link>https://undocumentedmatlab.com/articles/udd-properties?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=udd-properties</link>
					<comments>https://undocumentedmatlab.com/articles/udd-properties#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 Mar 2011 18:00:17 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[schema.prop]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2156</guid>

					<description><![CDATA[<p>UDD provides a very convenient way to add customizable properties to existing Matlab object handles</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/udd-properties">UDD Properties</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/displaying-hidden-handle-properties" rel="bookmark" title="Displaying hidden handle properties">Displaying hidden handle properties </a> <small>I present two ways of checking undocumented hidden properties in Matlab Handle Graphics (HG) handles...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties" rel="bookmark" title="getundoc &#8211; get undocumented object properties">getundoc &#8211; get undocumented object properties </a> <small>getundoc is a very simple utility that displays the hidden (undocumented) properties of a specified handle object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Donn Shull continues his series of articles on Matlab&#8217;s undocumented UDD mechanism. Today, Donn explains how to use and customize UDD properties.</i></p>
<h3 id="meta-data">Properties meta-data</h3>
<p>The UDD system is a class system. UDD packages, classes, events, and properties are all classes. In this section we will take a closer look at property classes.<br />
As we have <a target="_blank" href="/articles/creating-a-simple-udd-class/">already shown</a>, properties are added to a UDD class by adding <code>schema.prop</code> calls to the schema.m class definition file. What this really means is that each property of a UDD class is itself a class object (<code>schema.prop</code>) with its own properties and methods. The methods of <code>schema.prop</code> are <i>loadobj()</i> and <i>saveobj()</i>, which are used to serialize objects of this class (i.e., storing them in a file or sending them elsewhere).<br />
It is <code>schema.prop</code>&#8216;s properties (so-called <i>meta-properties</i>) that interest us most:</p>
<table>
<tr>
<th bgcolor="#D0D0D0">Property</th>
<th bgcolor="#D0D0D0">Data Type</th>
<th bgcolor="#D0D0D0">Description</th>
</tr>
<tr>
<td bgcolor="#E7E7E7">AccessFlags</td>
<td bgcolor="#E7E7E7">Matlab structure</td>
<td bgcolor="#E7E7E7">Controls which objects can access (read/modify) the property</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">CaseSensitive</td>
<td bgcolor="#E7E7E7">on/off</td>
<td bgcolor="#E7E7E7">Determines if the exact case is required to access the property (i.e., can we use &#8216;casesensitive&#8217; instead of &#8216;CaseSensitive&#8217;)</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">DataType</td>
<td bgcolor="#E7E7E7">string</td>
<td bgcolor="#E7E7E7">The underlying object&#8217;s property data type, set by the constructor</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Description</td>
<td bgcolor="#E7E7E7">string</td>
<td bgcolor="#E7E7E7">This can hold a description of the property (normally empty)</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">FactoryValue</td>
<td bgcolor="#E7E7E7">As specified by DataType</td>
<td bgcolor="#E7E7E7">This is used to provide an initial or default property value</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">GetFunction</td>
<td bgcolor="#E7E7E7">Function handle</td>
<td bgcolor="#E7E7E7">A function handle that is called whenever the property value is read</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Name</td>
<td bgcolor="#E7E7E7">string</td>
<td bgcolor="#E7E7E7">The name of the property, also set by the constructor</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">SetFunction</td>
<td bgcolor="#E7E7E7">Function handle</td>
<td bgcolor="#E7E7E7">A function handle that is called whenever the properties value is changed</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Visible</td>
<td bgcolor="#E7E7E7">on/off</td>
<td bgcolor="#E7E7E7">Determines if a property will be displayed by the <i><b>get</b></i> method for a UDD object</td>
</tr>
</table>
<p>We can manipulate the values of these meta-properties to control various aspects of our property:</p>
<pre lang="matlab">
% Create instance of simple.object
>> a = simple.object('a');
% Find the Value property and list its meta-properties
% We can manipulate these meta-properties within limits
>> a.findprop('Value').get
            Name: 'Value'
     Description: ''
        DataType: 'single'
    FactoryValue: 7.3891
     AccessFlags: [1x1 struct]
         Visible: 'on'
     GetFunction: []
     SetFunction: []
>> prop.Visible = 'off';  % i.e. hidden property (see below)
>> prop.AccessFlags.PublicSet = 'off';   % i.e. read-only
>> prop.AccessFlags.PublicGet = 'on';
% Find the DataType meta-property of the Value property
% This meta-property and all other schema.prop base class properties are fixed
>> a.findprop('Value').findprop('DataType').get
            Name: 'DataType'
     Description: ''
        DataType: 'string'
    FactoryValue: ''
           ...
</pre>
<h3 id="new-prop">Adding properties to existing objects in run-time</h3>
<p><code>schema.prop</code> is a very useful tool &#8211; it can be used to add new properties to existing object handles, even after these objects have been created. For example, let&#8217;s add a new property (<b>MyFavoriteBlog</b>) to a standard figure handle:</p>
<pre lang="matlab">
>> p=schema.prop(handle(gcf), 'MyFavoriteBlog','string')
p =
	schema.prop
>> set(gcf,'MyFavoriteBlog','UndocumentedMatlab.com')
>> get(gcf,'MyFavoriteBlog')
ans =
UndocumentedMatlab.com
</pre>
<p>Using this simple mechanism, we can add meaningful typed user data to any handle object. A similar functionality can be achieved via the <i><b>setappdata/getappdata</b></i> functions. However, the property-based approach above is much &#8220;cleaner&#8221; and more powerful, since we have built-in type checks, property-change event listeners and other useful goodies.</p>
<h3 id="DataType">Property data types</h3>
<p>In the article on <a target="_blank" href="/articles/creating-a-simple-udd-class/">creating UDD objects</a> we saw that the <b>Name</b> and <b>DataType</b> meta-properties are set by the <code>schema.prop</code> constructor. <b>Name</b> must be a valid Matlab variable name (see <i><b>isvarname</b></i>).<br />
<b>DataType</b> is more interesting: There are two equivalent universal data types, <code>'mxArray'</code>, and <code>'MATLAB array'</code>. With either of these two data types a property can be set to a any Matlab type. If we use a more specific data type (e.g., &#8216;string&#8217;, &#8216;double&#8217; or &#8216;handle&#8217;), Matlab automatically ensures the type validity whenever the property value is modified. In our <code>simple.object</code> we use &#8216;double&#8217; and &#8216;string&#8217;. You can experiment with these and see that the <b>Value</b> property will only allow scalar numeric values and the <b>Name</b> property will only allow character values:</p>
<pre lang="matlab">
>> set(obj, 'Value', 'abcd')
??? Parameter must be scalar.
>> obj.Value='abcd'
??? Parameter must be scalar.
>> obj.Name=123
??? Parameter must be a string.
</pre>
<p>The following table lists the basic UDD data types:</p>
<table>
<tr>
<th bgcolor="#D0D0D0">Category</th>
<th bgcolor="#D0D0D0">Data Type</th>
</tr>
<tr>
<td bgcolor="#E7E7E7">Universal</td>
<td bgcolor="#E7E7E7">MATLAB array, mxArray</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Numeric Scalars</td>
<td bgcolor="#E7E7E7">bool, byte, short, int, long, float, double</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Numeric Vectors</td>
<td bgcolor="#E7E7E7">Nints, NReals</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Specialized Numeric</td>
<td bgcolor="#E7E7E7">color, point, real point, real point3, rect, real rect</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Enumeration</td>
<td bgcolor="#E7E7E7">on/off</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Strings</td>
<td bgcolor="#E7E7E7">char, string, NStrings, string vector</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Handle</td>
<td bgcolor="#E7E7E7">handle, handle vector, MATLAB callback, GetFunction, SetFunction</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Java</td>
<td bgcolor="#E7E7E7">Any java class recognized by Matlab</td>
</tr>
</table>
<h3 id="user-types">User-defined data types</h3>
<p>While this is an extensive list, there are some obvious types missing. For example there are no unsigned integer types. To handle this UDD provides two facilities for creating your own data types. One is the <code>schema.EnumType</code>. As you can see, Matlab has had a form of enumerations for a really long time not just the last few releases. The other facility is <code>schema.UserType</code>.<br />
With these two classes you can create any specialized data type you need. One word of caution: once you have created a new UDD data type it exists for the duration of that Matlab session. There is no equivalent of the <i><b>clear classes</b></i> mechanism for removing a data type. In addition once a new data type has been defined it cannot be redefined until Matlab is restarted.<br />
Let&#8217;s use a <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/280282">problem discussed in the CSSM forum</a> as example. The essence of the problem is the need to flag a graphic line object as either editable or not. The proposed proposed is to add a new <b>Editable</b> property to an existing line handle. We will use <code>schema.EnumType</code> to create a new type named <code>'yes/no'</code> so that the new property could accept only &#8216;yes&#8217; and &#8216;no&#8217; values:</p>
<pre lang="matlab">
function tline = taggedLine(varargin)
%TAGGEDLINE create a line with Editable property
%
%   TLINE = TAGGEDLINE(VARARGIN) create a new handle graphics line
%   and add 'Ediatable' property to line. Default property value is 'yes'.
%
%   INPUTS:
%       VARARGIN  : property value pairs to pass to line
%
%   OUTPUTS:
%       TLINE     : hg line object with Editable property
    % If undefined define yes/no datatype</font>
    if isempty(findtype('yes/no'))
        schema.EnumType('yes/no', {'yes', 'no'});
    end
    tline = line(varargin{:});
    schema.prop(tline, 'Editable', 'yes/no');
end
</pre>
<p>It is necessary to test for the existence of a type before defining it, since trying to redefine a type will generate an error.<br />
We can use this new <i>taggedLine()</i> function to create new line objects with the additional <b>Editable</b> property. Instead of adding a new property to the line class we could have defined a new class as a subclass of line:</p>
<pre lang="matlab">
function schema()
%SCHEMA  hg package definition function
    schema.package('hg');
end
</pre>
<p>We create our class definition as a subclass of the handle graphics line class:</p>
<pre lang="matlab">
function schema()
%SCHEMA  hg.taggedline class definition function
    % package definition
    superPackage = findpackage('hg');
    pkg = findpackage('hg');
    % class definition
    c = schema.class(pkg, 'taggedline', findclass(superPackage, 'line'));
    if isempty(findtype('yes/no'))
        schema.EnumType('yes/no', {'yes', 'no'});
    end
    % add properties to class
    schema.prop(c, 'Editable', 'yes/no');
end
</pre>
<p>And our constructor is:</p>
<pre lang="matlab">
function self = taggedline
%OBJECT constructor for the simple.object class
    self = hg.taggedline;
end
</pre>
<p>Here we have placed the <code>schema.EnumType</code> definition in the class definition function. It is usually better to place type definition code in the package definition function, which is executed prior to any of the package classes and available in all classes. But in this particular case we are extending the built-in <code>hg</code> package and because <code>hg</code> is already defined internally, our package definition code is never actually executed.<br />
The <code>schema.UserType</code> has the following constructor syntax:</p>
<pre lang="matlab">
schema.UserType('newTypeName', 'baseTypeName', typeCheckFunctionHandle)
</pre>
<p>For example, to create a user-defined type for unsigned eight-bit integers we might use the following code:</p>
<pre lang="matlab">
schema.UserType('uint8', 'short', @check_uint8)
function check_uint8(value)
%CHECK_UINT8 Check function for uint8 type definition
    if isempty(value) || (value < 0) || (value > 255)
        error('Value must be a scalar between 0 and 255');
    end
end
</pre>
<h3 id="hidden">Hidden properties</h3>
<p><b>Visible</b> is an <code>'on/off'</code> meta-property that controls whether or not a property is displayed when using the <i><b>get</b></i> function without specifying the property name. Using this mechanism we can easily detect hidden undocumented properties. For example:</p>
<pre lang="matlab">
>> for prop = get(classhandle(handle(gcf)),'Properties')'
       if strcmpi(prop.Visible,'off'), disp(prop.Name); end
   end
BackingStore
CurrentKey
CurrentModifier
Dithermap
DithermapMode
DoubleBuffer
FixedColors
HelpFcn
HelpTopicMap
MinColormap
JavaFrame
OuterPosition
ActivePositionProperty
PrintTemplate
ExportTemplate
WaitStatus
UseHG2
PixelBounds
HelpTopicKey
Serializable
ApplicationData
Behavior
XLimInclude
YLimInclude
ZLimInclude
CLimInclude
ALimInclude
IncludeRenderer
</pre>
<p>Note that hidden properties such as these are accessible via <i><b>get/set</b></i> just as any other property. It is simply that they are not displayed when you run <i><b>get(gcf)</b></i> or <i><b>set(gcf)</b></i> &#8211; we need to specifically refer to them by their name: <i><b>get(gcf</b>,&#8217;UseHG2&#8242;)</i>. Many other similar hidden properties are <a target="_blank" href="/articles/tag/hidden-property/">described in this website</a>.<br />
You may have noticed that the <b>CaseSensitive</b> meta-property did not show up above when we used <i><b>get</b></i> to show the meta-properties of our <b>Value</b> property. This is because <b>CaseSensitive</b> has its own <b>Visible</b> meta-property set to <code>'off'</code> (i.e., hidden).</p>
<h3 id="additional">Additional meta-properties</h3>
<p><b>FactoryValue</b> is used to set an initial value for the property whenever a new <code>simple.object</code> instance is created.<br />
<b>GetFunction</b> and <b>SetFunction</b> were described in last week&#8217;s article, <a href="/articles/hierarchical-systems-with-udd/">Creating a UDD Hierarchy</a>.<br />
<b>AccessFlags</b> is a Matlab structure of <code>'on/off'</code> fields that control what happens when the property is accessed:</p>
<table>
<tr>
<th bgcolor="#D0D0D0">Fieldname</th>
<th bgcolor="#D0D0D0">Description</th>
</tr>
<tr>
<td bgcolor="#E7E7E7">PublicSet</td>
<td bgcolor="#E7E7E7">Controls setting the property from code external to the class</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">PublicGet</td>
<td bgcolor="#E7E7E7">Controls reading the property value from code external to the class</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">PrivateSet</td>
<td bgcolor="#E7E7E7">Controls setting the property from internal class methods</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">PrivateGet</td>
<td bgcolor="#E7E7E7">Controls reading the property value from internal class methods</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Init</td>
<td bgcolor="#E7E7E7">Controls initializing the property using <b>FactoryValue</b> in the class definition file</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Default</td>
<td bgcolor="#E7E7E7">??? (Undocumented, no examples exist)</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Reset</td>
<td bgcolor="#E7E7E7">Controls initializing the property using <b>FactoryValue</b> when executing the built-in <i><b>reset</b></i> function</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Serialize</td>
<td bgcolor="#E7E7E7">Controls whether this object can be serialized</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Copy</td>
<td bgcolor="#E7E7E7">Controls whether to pass the property&#8217;s current value to a copy</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">Listener</td>
<td bgcolor="#E7E7E7">Controls whether property access events are generated or not</td>
</tr>
<tr>
<td bgcolor="#E7E7E7">AbortSet</td>
<td bgcolor="#E7E7E7">Controls whether property set events are generated when a <i><b>set</b></i> operation will not change the property&#8217;s value</td>
</tr>
</table>
<p>The <b>CaseSensitive</b> meta-property has <b>AccessFlag.Init</b> = <code>'off'</code>. This means that properties added to a class definition file are always case insensitive.<br />
Another interesting fact is that properties can be abbreviated as long as the abbreviation is unambiguous. Using our <code>simple.object</code> as an example:</p>
<pre lang="matlab">
>> a = simple.object('a');
>> a.n  % abbreviation of Name
ans =
a
>> a.v  % abbreviation of Value
ans =
    0.0000
</pre>
<p>It is considered poor programming practice to use either improperly cased, or abbreviated names when writing code. It is difficult to read, debug and maintain. But show me a Matlab programmer who has never abbreviated <b>Position</b> as &#8216;pos&#8217;&#8230;<br />
<i>Note: for completeness&#8217; sake, read yesterday&#8217;s post on <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/loren/2011/03/08/common-design-considerations-for-object-properties/">MCOS properties</a> on Loren&#8217;s blog, written by Dave Foti, author of the original UDD code. Dave&#8217;s post describes the fully-documented MCOS mechanism, which is newer than the undocumented UDD mechanism described here. As mentioned earlier, whereas UDD existed (and still exists) in all Matlab 7 releases, MCOS is only available since R2008a. UDD and MCOS co-exist in Matlab since R2008a. MCOS has definite advantages over UDD, but cannot be used on pre-2008 Matlab releases. Different development and deployment requirements may dictate using either UDD or MCOS (or both). Another pre-R2008a alternative is to use Matlab&#8217;s obsolete yet documented <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/pdf_doc/matlab/pre-version_7.6_oop.pdf">class system</a>.</i><br />
In the next installment of this series we will take a look at UDD events and listeners.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/udd-properties">UDD Properties</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/displaying-hidden-handle-properties" rel="bookmark" title="Displaying hidden handle properties">Displaying hidden handle properties </a> <small>I present two ways of checking undocumented hidden properties in Matlab Handle Graphics (HG) handles...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties" rel="bookmark" title="getundoc &#8211; get undocumented object properties">getundoc &#8211; get undocumented object properties </a> <small>getundoc is a very simple utility that displays the hidden (undocumented) properties of a specified handle object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/udd-properties/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
	</channel>
</rss>
