<?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>Donn Shull &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/donn-shull/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 16 Sep 2015 17:26:44 +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>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 fetchpriority="high" 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>Simulink Data Dictionary</title>
		<link>https://undocumentedmatlab.com/articles/simulink-data-dictionary?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=simulink-data-dictionary</link>
					<comments>https://undocumentedmatlab.com/articles/simulink-data-dictionary#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 11 Feb 2015 18:00:11 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></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[MCOS]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Simulink]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5571</guid>

					<description><![CDATA[<p>Simulink contains undocumented public API for access to its data dictionary functionality. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/simulink-data-dictionary">Simulink Data Dictionary</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/improving-simulink-performance" rel="bookmark" title="Improving Simulink performance">Improving Simulink performance </a> <small>Simulink simulation run-time performance can be improved by orders of magnitude by following some simple steps. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sparse-data-math-info" rel="bookmark" title="Sparse data math info">Sparse data math info </a> <small>Matlab contains multiple libraries for handling sparse data. These can report very detailed internal info. ...</small></li>
<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/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I wish to welcome guest blogger <a target="_blank" rel="nofollow" href="http://aetoolbox.com">Donn Shull</a>. Donn has previously written a series of articles on Matlab&#8217;s previous-generation class-object system (<a target="_blank" href="/?s=UDD">UDD</a>). Today Donn explores a little-known yet quite useful aspect of Simulink.</i></p>
<h3 id="Introduction">Introduction</h3>
<p>In 2014, MathWorks introduced the Simulink Data Dictionary. This new feature provides the ability to store <code>Data Types</code>, <code>Parameters</code>, and <code>Signals</code> in database files. This is great news for embedded systems developers who want the flexibility of using data objects and want to avoid using the base workspace with its potential for data corruption.<br />
In its initial implementation, the data dictionary interface is provided by the <a target="_blank" rel="nofollow" href="https://www.mathworks.com/help/simulink/ug/search-and-edit-using-model-explorer.html">Simulink Model Explorer</a>. The GUI interface is clean, intuitive, and easy to use. This interface supports importing and exporting dictionaries to m files and mat files.<br />
Unfortunately, in production code generation environments there is frequently a need to interface this data with external tools such as software specification systems, documentation generators, and calibration tools. MathWorks have not published an API for accessing dictionaries from code, indicating that it may possibly be available in a future release. Today, we will look at some portions of the undocumented API for Simulink Data Dictionaries.<br />
<center><a target="_blank" rel="nofollow" href="https://web.archive.org/web/20150402031355im_/http://www.mathworks.com/help/simulink/ug/importfrombws.png"><img decoding="async" alt="Simulink F14 model using data dictionary" src="https://web.archive.org/web/20150402031355im_/http://www.mathworks.com/help/simulink/ug/importfrombws.png" title="Simulink F14 model using data dictionary" width="100%" style="max-width: 700px;" /></a></center><br />
<span id="more-5571"></span></p>
<h3 id="background">Some background information</h3>
<p>Simulink Data Dictionaries exist as files having a standard file extension of <i>.sldd</i>. Dictionary files can be opened with the <i><b>open</b></i> function, which in turn calls <i><b>opensldd</b></i>. This opens the file and launches the Simulink Model Explorer with the selected dictionary node. When a dictionary is opened, a cached copy is created. While working with a dictionary, changes are made to the cached copy. The dictionary file is only changed when the changes are saved by issuing the relevant command. Until the cached copy is saved, it is possible to view differences between the file and the cached copy, and revert any unwanted changes. The file maintains the date, time, and author of the last saved change, but no information about previous revisions.<br />
From the Model Explorer it is possible to add items to a dictionary from a model, the base workspace, or by creating new items. We can associate a Simulink model with a dictionary by using the model properties dropdown in the Simulink editor.<br />
Using data dictionaries it is possible to tailor a model&#8217;s code generation for different targets, simply by changing the dictionary that is being used.</p>
<h3 id="API">The Simulink Data Dictionary API</h3>
<p>Programmatic access to Simulink Data Dictionaries is provided by the undocumented MCOS package <code>Simulink.dd</code>. We will look at two package functions and a few methods of the <code>Simulink.dd.Connection</code> class. These provide the basic ability to work with dictionaries from within our m code.</p>
<h4 id="create">Creating and Opening Dictionary Files</h4>
<p>Dictionary files are created with the package function <i>create</i>:</p>
<pre lang='matlab'>hDict = Simulink.dd.create(dictionaryFileName);</pre>
<p>Existing dictionary files are opened using the package function <i>open</i>:</p>
<pre lang='matlab'>hDict = Simulink.dd.open(dictionaryFileName);</pre>
<p>In both cases the functions return a handle of type <code>Simulink.dd.Connection</code> to the named dictionary file.</p>
<h4 id="modify">Modifying a Dictionary</h4>
<p>We can use methods of the <code>Simulink.dd.Connection</code> instance to modify an open dictionary. Dictionaries are organized into two sections: The <code>Configurations</code> section contains <code>Simulink.ConfigSet</code> entries, while <code>Parameter</code>, <code>Signal</code>, and <code>DataType</code> items are placed in the <code>Global</code> section. We can get a list of the items in a section using the <i>getChildNames</i> method:</p>
<pre lang='matlab'>childNamesList = hDict.getChildNames(sectionName);</pre>
<p>Adding and removing items from a section are done using the <i>insertEntry</i> and <i>deleteEntry</i> methods, respectively:</p>
<pre lang='matlab'>
hDict.insertEntry(sectionName, entryName, object)
hDict.deleteEntry(sectionName, entryName)
</pre>
<p>Modifying an existing entry is done using the <i>getEntry</i>, and <i>setEntry</i> methods:</p>
<pre lang='matlab'>
workingCopy = hDict.getEntry(sectionName.entryName)
% modify workingCopy
hDict.setEntry(sectionName.entryName, workingCopy)
</pre>
<p>A collection of objects from the base workspace can be added to a dictionary using the <i>importFromBaseWorkspace</i> method:</p>
<pre lang='matlab'>hDict.importFromBaseWorkspace(sectionName, overwriteExisitngObjectsFlag, deleteFromBaseWorkspaceFlag, cellArrayOfNames)</pre>
<p>Additional dictionary manipulations are possible using the <i>evalin</i> and <i>assignin</i> methods:</p>
<pre lang='matlab'>
hDict.evalin(commandString)
hDict.assignin(variableName, variable)
</pre>
<h4 id="close">Closing a Dictionary</h4>
<p>Finalizing a dictionary session is done with the <i>saveChanges</i>, <i>close</i>, and <i>delete</i> methods:</p>
<pre lang='matlab'>
hDict.saveChanges
hDict.close
hDict.delete
</pre>
<h3 id="example">Example: Migrate Single Model to Use Dictionary</h3>
<p>This example is an adaptation of <a target="_blank" rel="nofollow" href="https://www.mathworks.com/help/simulink/ug/migrate-models-to-use-dictionary.html">MathWorks&#8217; interactive example of the same title</a>, using programmatic Matlab commands rather than GUI interactions.</p>
<ol>
<li>Start by using <i><b>load_system</b></i> to open the f14 model. This opens the model and executes the <i>PreLoadFcn</i> callback, which loads design data into the base workspace, without opening the Simulink block diagram editor:
<pre lang='matlab'>load_system('f14');</pre>
</li>
<li>Use the Simulink package function <i>findVars</i> to find the variables used by the model:
<pre lang='matlab'>usedVariables = Simulink.findVars('f14');</pre>
</li>
<li>Next, use the <i>create</i> package function to create and open a new Simulink Data Dictionary:
<pre lang='matlab'>hDict = Simulink.dd.create('f14_data_dictionary.sldd');</pre>
</li>
<li>Attach the newly created dictionary to the model:
<pre lang='matlab'>set_param('f14', 'DataDictionary', 'f14_data_dictionary.sldd');</pre>
</li>
<li>Use one of the API methods to add these variables to the Data Dictionary:
<pre lang='matlab'>
overWrite = true;
deleteFromWorkspace = false;
for n = 1:numel(usedVariables)
    if strcmp(usedVariables(n).Source, 'base workspace')
        hDict.importFromBaseWorkspace(overWrite, deleteFromWorkspace, {usedVariables(n).Name});
    end
end
</pre>
</li>
<li>Save the changes made to the dictionary:
<pre lang='matlab'>hDict.saveChanges;</pre>
</li>
<li>Clean up and we are done:
<pre lang='matlab'>
hDict.close;
hDict.delete;
clear hDict;
</pre>
</li>
</ol>
<h3 id="notes">Final notes</h3>
<p>MathWorks have recognized the value of data dictionaries for a long time. In 2006, MathWorker Tom Erkkinen <a target="_blank" rel="nofollow" href="http://www.eetimes.com/document.asp?doc_id=1272777">published a paper</a> about multitarget modeling using data dictionaries. The <code>Simulink.dd</code> package was added to Matlab in R2011b, and the <code>DataDictionary</code> parameter was added to Simulink models in R2012a. MathWorks have also <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/153367-how-to-eval-expressions-in-simulink-data-dictionaries">indicated</a> that a user API for Simulink Data Dictionaries may be in the works. Until it is released we can make do with the undocumented API.<br />
<b><u>Update March 7, 2015</u></b>: Matlab release R2015a now includes a fully documented <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/simulink/slref/simulink.data.dictionary-class.html"><code>Simulink.data.Dictionary</code></a> class, which works in a very similar manner. Users of R2015a or newer should use this new <code>Simulink.data.Dictionary</code> class, while users of previous Matlab releases can use the <code>Simulink.dd</code> class presented in this article.<br />
Have you made some good use of this data-dictionary functionality in your project? If so, please share your experience in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/simulink-data-dictionary">Simulink Data Dictionary</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/improving-simulink-performance" rel="bookmark" title="Improving Simulink performance">Improving Simulink performance </a> <small>Simulink simulation run-time performance can be improved by orders of magnitude by following some simple steps. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sparse-data-math-info" rel="bookmark" title="Sparse data math info">Sparse data math info </a> <small>Matlab contains multiple libraries for handling sparse data. These can report very detailed internal info. ...</small></li>
<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/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/simulink-data-dictionary/feed</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
			</item>
		<item>
		<title>Extending a Java class with UDD</title>
		<link>https://undocumentedmatlab.com/articles/extending-a-java-class-with-udd?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=extending-a-java-class-with-udd</link>
					<comments>https://undocumentedmatlab.com/articles/extending-a-java-class-with-udd#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 29 Mar 2012 14:32:46 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[schema.class]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2824</guid>

					<description><![CDATA[<p>Java classes can easily be extended in Matlab, using pure Matlab code. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/extending-a-java-class-with-udd">Extending a Java class with UDD</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/java-class-access-pitfalls" rel="bookmark" title="Java class access pitfalls">Java class access pitfalls </a> <small>There are several potential pitfalls when accessing Matlab classes from Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I welcome Donn Shull, with another article about Matlab&#8217;s internal UDD mechanism</i></p>
<h3 id="Introduction">Extending a Java class with UDD</h3>
<p>During the <a target="_blank" href="/?s=UDD">series on UDD</a>, we have mentioned the connection between UDD and Java. In <a target="_blank" href="/articles/udd-events-and-listeners/">UDD Events and Listeners</a> we described how in Matlab, each Java object can have a UDD companion. In <a target="_blank" href="/articles/hierarchical-systems-with-udd/">Hierarchical Systems with UDD</a> we briefly noted that a UDD hierarchy may be passed to Java. In the numerous posts on handle graphics and callbacks, Yair has discussed the UDD packages <code>javahandle</code> and <code>javahandle_withcallbacks</code>. Based on this information, it seems reasonable to speculate that it may be possible to extend a Java class with UDD using UDD&#8217;s class inheritance mechanism.<br />
This can be extremely useful in two cases:</p>
<ul>
<li>You don&#8217;t know Java but found a Java class you would like to use in Matlab, it just needs minor modifications for your specific needs</li>
<li>You do know Java, but don&#8217;t have access to the original source code, and choose to extend the Java class with Matlab code, rather than Java code</li>
</ul>
<p>Today I will show how this can be done using a simple example. Our example will illustrate the following things:</p>
<ol>
<li>Subclassing a Java class with UDD</li>
<li>Adding UDD properties to the to the subclass</li>
<li>Overloading a Java method with Matlab code</li>
<li>Directly accessing the superclass methods</li>
</ol>
<p>The example will show extending Java socket classes to provide a simple method for communication between two Matlab sessions. The protocol has been kept purposely simple and is not robust. Additional work would need to be done to create a real-life socket-based communication between Matlab systems (see for example <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/24524-tcpip-communications-in-matlab">this</a> FEX submission).<br />
Today&#8217;s example consists of two subclasses: a subclass of <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html"><code>java.net.ServerSocket</code></a> and a subclass of <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html"><code>java.net.Socket</code></a>. The protocol will be sending strings back and forth between the two sessions. In each direction the information exchange will consist of two bytes containing the string length, followed by the actual string. The entire source code can be downloaded <a target="_blank" href="/files/simple2.zip">from here</a>.</p>
<h3 id="ServerSocket">Creating the simple.ServerSocket class</h3>
<p>As in the UDD series, we will use the simple package for our classes and in this package create a <code>ServerSocket</code> class and a <code>Socket</code> class. Recall the simple package definition class is placed in a file named <i>schema.m</i> in a directory called <i>@simple</i>, placed somewhere on the Matlab path. <i>schema.m</i> consists of:</p>
<pre lang='matlab'>
function schema()
%SCHEMA  simple package definition function.
   schema.package('simple');
end
</pre>
<p>In our <code>ServerSocket</code> class we will add three UDD properties and overload two of the Java class methods. It is worth noting that our final class will have all the parent Java classes public properties and methods and if necessary we can access the parent or super class methods directly. As before, we create a subfolder of the <i>@simple</i> folder named <i>@ServerSocket</i>; in this folder we place four files:</p>
<ol>
<li><i>schema.m</i> &#8211; the class definition file</li>
<li><i>ServerSocket.m</i> &#8211; the class constructor</li>
<li><i>accept.m</i> &#8211; one of the Java methods that we will overload</li>
<li><i>bind.m</i> &#8211; the other Java method that we will overload</li>
</ol>
<p>At the beginning of our <i>schema.m</i> file, we will use the following code to subclass the Java class:</p>
<pre lang='matlab'>
function schema
%SCHEMA simple.ServerSocket class definition function.
    % parent schema.class definition
    javaPackage = findpackage('javahandle');
    javaClass = findclass(javaPackage, 'java.net.ServerSocket');
    % class package (schema.package)
    simplePackage = findpackage('simple');
    % class definition
    simpleClass = schema.class(simplePackage, 'ServerSocket', javaClass);
</pre>
<p>Here, we use <i><b>findpackage</b></i> and <i><b>findclass</b></i> to obtain the <i><b>schema.class</b></i> for the Java class that we are going to use as our parent. We then obtain a handle to the containing package, and finally use the subclass variation to define our <code>ServerSocket</code> as a variation of the Java parent&#8217;s <i><b>schema.class</b></i>.<br />
Next, in the class definition file we place the code to define the signatures for the methods we are overloading:</p>
<pre lang='matlab'>
    % accept.m overloads java accept method and adds communication protocol
    m = schema.method(simpleClass, 'accept');
    s = m.Signature;
    s.varargin    = 'off';
    s.InputTypes  = {'handle'};
    s.OutputTypes = {'string'};
    % bind.m overloads java bind method
    m = schema.method(simpleClass, 'bind');
    s = m.Signature;
    s.varargin    = 'off';
    s.InputTypes  = {'handle'};
    s.OutputTypes = {};be
</pre>
<p>Finally, we add three UDD properties to the class: The first will be used to hold a string representation of the address of our <code>ServerSocket</code>; the second will store the communication port number; the third is a handle property that will hold the reference to the socket used by the actual communication.</p>
<pre lang='matlab'>
    % holds remote address as a matlab string
    p = schema.prop(simpleClass, 'address', 'string');
    p.FactoryValue = 'localhost';
    % holds remote port as a matlab int
    p = schema.prop(simpleClass, 'port', 'int16');
    p.FactoryValue = 2222;
    % holds a handle reference to the socket created in the accept method
    p = schema.prop(simpleClass, 'socket', 'handle');
end
</pre>
<p>We now need to write our overloaded methods. The <i>bind</i> method is simple: it first creates a Java internet address using the new address and port properties; then it uses the standard Java class methods to call the superclass&#8217;s <i>bind</i> method with the specified internet address:</p>
<pre lang='matlab'>
function bind(this)
    % use the object socket and port port properties to bind this instance
    % to a address calling the superclass bind method
    inetAddress = java.net.InetSocketAddress(this.address, this.port);
    this.java.bind(inetAddress);
end
</pre>
<p>The overloaded <i>accept</i> method is a bit more complicated and crude: It starts by calling the superclass <i>accept</i> method to create a communication socket and stores the created socket in our class&#8217;s socket property. Then it goes into an infinite loop of waiting for incoming commands, uses <i><b>evalc</b></i> to execute them, and returns the captured result to the caller. The only way out of this loop is using Ctrl-C from the keyboard.</p>
<pre lang='matlab'>
function accept(this)
    % use the superclass accept
    this.socket = handle(this.java.accept);
    % infinite loop use ctrl-c to exit
    while 1
        % wait for a command then execute it capturing output
        while this.socket.getInputStream.available < 2
        end
        msb = this.socket.getInputStream.read;
        lsb = this.socket.getInputStream.read;
        numChar = 256 * msb + lsb;
        cmd = uint8(zeros(1, numChar));
        for index = 1:numChar
            cmd(index) = this.socket.getInputStream.read;
        end
        result = evalc(char(cmd));
        % send the result back to the calling system
        len = numel(result);
        msb = uint8(floor(len/256));
        lsb = uint8(mod(len,256));
        this.socket.getOutputStream.write(uint8([msb, lsb, result]));
    end
end
</pre>
<h3 id="Socket">Creating the simple.Socket class</h3>
<p>The <code>simple.Socket</code> class is created like <code>ServerSocket</code>, this time in the <i>@Socket</i> folder under the <i>@simple</i> folder. In this subclass we add properties for the address and port, just as in <code></code><code>ServerSocket</code>. We overload the superclass's <i>connect</i> method with our own variant, and add a new method to make the remote calls to the <code>ServerSocket</code> running in another Matlab instance. Beginning with the <i>schema.m</i> file we have:</p>
<pre lang="matlab">
function schema
%SCHEMA simple.Socket class definition function.
    % package definition
    simplePackage = findpackage('simple');
    javaPackage = findpackage('javahandle');
    javaClass = findclass(javaPackage, 'java.net.Socket');
    % class definition
    simpleClass = schema.class(simplePackage, 'Socket', javaClass);
    % define class methods
    % connect.m overloads java connect method
    m = schema.method(simpleClass, 'connect');
    s = m.Signature;
    s.varargin    = 'off';
    s.InputTypes  = {'handle'};
    s.OutputTypes = {};
    % remoteEval.m matlab method for remote evaluation of Matlab commands
    m = schema.method(simpleClass, 'remoteEval');
    s = m.Signature;
    s.varargin    = 'off';
    s.InputTypes  = {'handle', 'string'};
    s.OutputTypes = {'string'};
    % add properties to this class
    % holds remote address as a Matlab string
    p = schema.prop(simpleClass, 'address', 'string');
    p.FactoryValue = 'localhost';
    % holds remote port as a Matlab int
    p = schema.prop(simpleClass, 'port', 'int16');
    p.FactoryValue = 2222;
end
</pre>
<p>The class constructor <i>Socket.m</i> is simply:</p>
<pre lang="matlab">
function skt = Socket
%SOCKET constructor for the simple.Socket class
    skt = simple.Socket;
end
</pre>
<p>The overloaded <i>connect</i> method is almost identical to the overloaded bind method we used for <code>ServerSocket</code>. We form a Java internet address from our new properties and then invoke the superclass&#8217;s <i>connect</i> Java method:</p>
<pre lang="matlab">
function connect(this)
%CONNECT overload of the java.net.Socket connect method
    % use the object address and port properties to connect to the remote
    % session via the superclass connect method
    inetAddress = java.net.InetSocketAddress(this.address, this.port);
    this.java.connect(inetAddress);
end
</pre>
<p>Finally, our <i>remoteEval</i> method is very similar to the loop portion of the overloaded accept method we wrote for <code>simple.ServerSocket</code>. We take the command string input and convert it into a series of bytes prepended by the length of the string, send it to the other Matlab session and wait for a response:</p>
<pre lang='matlab'>
function result = remoteEval(this, cmd)
%REMOTEEVAL evaluate a Matlab command on a remotely connected Matlab
    % The command string is sent as a series of bytes preceded by a pair of
    % bytes which represents the length of the string
    cmd = uint8(cmd);
    len = numel(cmd);
    msb = uint8(floor(len/256));
    lsb = uint8(mod(len,256));
    this.getOutputStream.write([msb, lsb, cmd]);
    % We will expect the remote session to return a string in the same format
    % as the command
    while this.getInputStream.available < 2
    end
    msb = this.getInputStream.read;
    lsb = this.getInputStream.read;
    numChar = 256 * msb + lsb;
    result = uint8(zeros(1, numChar));
    for index = 1:numChar
        result(index) = this.getInputStream.read;
    end
    result = char(result);
end
</pre>
<h3 id="Usage">Using simple.ServerSocket and simple.Socket to communicate between Matlab sessions</h3>
<p>To use this example, add the zip contents to your Matlab path, then open an instance of Matlab and issue the following commands:</p>
<pre lang='matlab'>
>> ss = simple.ServerSocket;
>> ss.bind;
>> ss.accept;
</pre>
<p>Then open another Matlab instance and issue these commands:</p>
<pre lang='matlab'>
>> s = simple.Socket;
>> s.connect;
</pre>
<p>At this point you can send commands from this Matlab instance (the client) to the first instance (the server) using the <i>remoteEval</i> method. The command will then be transmitted to the server, executed, and the server will return the captured string result to the client:</p>
<pre lang="matlab">
>> remoteResult = s.remoteEval('pi')
remoteResult =
    3.1416
</pre>
<p>The defaults are for localhost and port 2222. These can be changed prior to using the server's <i>bind</i> method and the client's <i>connect</i> method. To keep things as simple as possible, error checking etc. has been left out, so this is just a demonstration and is far from robust.<br />
There are some things to note about our new classes. If we type <i><b>methods</b>(s)</i> or <i>s.methods</i> at the Matlab command prompt in our <code>simple.Socket</code> session we obtain:</p>
<pre lang="matlab">
>> s.methods
Methods for class simple.Socket:
Socket                     getOOBInline               isClosed                   setReuseAddress
bind                       getOutputStream            isConnected                setSendBufferSize
close                      getPort                    isInputShutdown            setSoLinger
connect                    getReceiveBufferSize       isOutputShutdown           setSoTimeout
equals                     getRemoteSocketAddress     java                       setSocketImplFactory
getChannel                 getReuseAddress            notify                     setTcpNoDelay
getClass                   getSendBufferSize          notifyAll                  setTrafficClass
getInetAddress             getSoLinger                remoteEval                 shutdownInput
getInputStream             getSoTimeout               sendUrgentData             shutdownOutput
getKeepAlive               getTcpNoDelay              setKeepAlive               toString
getLocalAddress            getTrafficClass            setOOBInline               wait
getLocalPort               hashCode                   setPerformancePreferences
getLocalSocketAddress      isBound                    setReceiveBufferSize
</pre>
<p>This shows that our <code>simple.Socket</code> class has all of the methods of the Java superclass, plus our added <code>remoteEval</code> method and the <code>java</code> method that was automatically added by Matlab. This means that all of the Java methods are methods of our class instance and the added <code>java</code> means that we can access the superclass methods from our class instance if the need arises. If we use the <i><b>struct</b></i> function which Yair has <a target="_blank" href="/articles/matlab-java-memory-leaks-performance/#struct">previously discussed</a>, we obtain:</p>
<pre lang="matlab">
>> struct(s)
ans =
              OOBInline: 0
                  Bound: 1
                Channel: []
                  Class: [1x1 java.lang.Class]
                 Closed: 0
              Connected: 1
            InetAddress: [1x1 java.net.Inet4Address]
          InputShutdown: 0
            InputStream: [1x1 java.net.SocketInputStream]
              KeepAlive: 0
           LocalAddress: [1x1 java.net.Inet4Address]
              LocalPort: 51269
     LocalSocketAddress: [1x1 java.net.InetSocketAddress]
         OutputShutdown: 0
           OutputStream: [1x1 java.net.SocketOutputStream]
      ReceiveBufferSize: 8192
    RemoteSocketAddress: [1x1 java.net.InetSocketAddress]
           ReuseAddress: 0
         SendBufferSize: 8192
               SoLinger: -1
              SoTimeout: 0
             TcpNoDelay: 0
           TrafficClass: 0
                address: 'localhost'
                   port: 2222
</pre>
<p>We see that we have access to all of the public properties of the Java superclass, as well as the UDD properties that we have added.</p>
<h3 id="Conclusion">Conclusion</h3>
<p>At the beginning of this post I said that this would be a simple non-robust communications method. In order to make this anything more than that, a number of things would need to be implemented, for example:</p>
<ul>
<li>Improve the <i>accept</i> method to exit after a timeout or when a connection has been made and then terminated</li>
<li>Add checksums and timeouts for communication to determine the reliability of the communication</li>
<li>Add a retry request protocol for instances of communication failure</li>
<li>Add support for any serializable Matlab type, not just strings</li>
</ul>
<p>The intent here was just to show that extending Java classes with Matlab is possible, relatively simple, and can be extremely useful. After all, with over 10 million Java developers out there, chances are that somebody somewhere has already posted a Java class that answers your exact need, or at least close enough that it can be used in Matlab with only some small modifications.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/extending-a-java-class-with-udd">Extending a Java class with UDD</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/java-class-access-pitfalls" rel="bookmark" title="Java class access pitfalls">Java class access pitfalls </a> <small>There are several potential pitfalls when accessing Matlab classes from Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/extending-a-java-class-with-udd/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Minimize/maximize figure window</title>
		<link>https://undocumentedmatlab.com/articles/minimize-maximize-figure-window?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=minimize-maximize-figure-window</link>
					<comments>https://undocumentedmatlab.com/articles/minimize-maximize-figure-window#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 May 2011 23:08:07 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2310</guid>

					<description><![CDATA[<p>Matlab figure windows can easily be maximized, minimized and restored using a bit of undocumented magic powder</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/minimize-maximize-figure-window">Minimize/maximize figure window</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/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/disable-entire-figure-window" rel="bookmark" title="Enable/disable entire figure window">Enable/disable entire figure window </a> <small>Disabling/enabling an entire figure window is impossible with pure Matlab, but is very simple using the underlying Java. This article explains how....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Over the past couple of years, I posted <a target="_blank" href="/articles/tag/javaframe/">several articles</a> using the <b>JavaFrame</b> property of the figure handle, which enables access to the GUI&#8217;s underlying Java peer object. Today, I show how using <b>JavaFrame</b> we can solve a very frequent user request on the Matlab CSSM forum.</p>
<h3 id="Problem">The problem</h3>
<p>Matlab figures can be maximized, minimized and restored by <em>interactively</em> clicking the corresponding icon (or menu item) on the figure window&#8217;s frame (the title bar). However, we often need to create maximized main-application windows, and wish to save the users the need to manually maximize the window. Moreover, we may sometimes even wish to prevent users from resizing a maximized main window.<br />
Unfortunately, Matlab does not contain any documented or supported way to <em>programmatically</em> maximize, minimize or restore a figure window.<br />
This is very strange considering the fact that these are such elementary figure operations. Moreover, these operations are supported internally (and have been for many releases already), as shown below. It is therefore difficult for me to understand why they were not added to the documented Matlab HG wrapper functionality a long time ago. I fail to understand why obscure features such as docking were added to the wrapper, but standard minimization and maximization were not.</p>
<h3 id="Maximization">Maximization</h3>
<p><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/?term=maximize+window">Several solutions</a> have been presented to this problem over the years. Let us start with the pressing question of figure maximization:<br />
Solutions that rely on documented Matlab features tend to compute the available screen size and resize the figure accordingly. The result is lacking in many respects: it does not account for the taskbar (neither in size nor in location, which is not necessarily at the bottom of the screen); it does not remove the window border as in regular maximized figures; and it often ignores extended desktops (i.e. an attached additional monitor).<br />
The solutions that do work properly all rely on undocumented features: Some use platform-specific native Windows API in a mex-file (Jan Simon&#8217;s recent <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/31437-windowapi">WindowAPI</a> submission really pushes the limit in this and other regards). Alternately, we can easily use the platform-independent <b>JavaFrame</b>:</p>
<pre lang='matlab'>
>> jFrame = get(handle(gcf),'JavaFrame')
jFrame =
com.mathworks.hg.peer.FigurePeer@cdbd96
>> jFrame.setMaximized(true);   % to maximize the figure
>> jFrame.setMaximized(false);  % to un-maximize the figure
</pre>
<h3 id="Minimization">Minimization</h3>
<p>To the best of my knowledge, there are no solutions for minimizing figure windows that use documented Matlab features. Again, this can be done using either native Windows API, or the platform-independent <b>JavaFrame</b>:</p>
<pre lang='matlab'>
>> jFrame.setMinimized(true);   % to minimize the figure
>> jFrame.setMinimized(false);  % to un-minimize the figure
</pre>
<h3 id="Notes">Usage notes</h3>
<p><b>Maximized</b> and <b>Minimized</b> are mutually-exclusive, meaning that no more than one of them can be 1 (or true) at any time. This is automatically handled – users only need to be aware that a situation in which a window is both maximized and minimized at the same time is impossible (duh!).<br />
There are several equivalent manners of setting <code>jFrame</code>&#8216;s <b>Maximized</b> and <b>Minimized</b> property values, and your choice may simply be a matter of aesthetics and personal taste:</p>
<pre lang='matlab'>
% Three alternative possibilities of setting Maximized:
jFrame.setMaximized(true);
set(jFrame,'Maximized',true);   % note interchangeable 1< =>true, 0< =>false
jFrame.handle.Maximized = 1;
</pre>
<p><code>jFrame</code> follows Java convention: the accessor method that retrieves boolean values is called <i>is&lt;Propname&gt;()</i> instead of <i>get&lt;Propname&gt;</i>. In our case: <i>isMaximized()</i> and <i>isMinimized()</i>:</p>
<pre lang='matlab'>
flag = jFrame.isMinimized;        % Note: isMinimized, not getMinimized
flag = get(jFrame,'Minimized');
flag = jFrame.handle.Minimized;
</pre>
<p>In some old Matlab releases, <code>jFrame</code> did not possess the <b>Maximized</b> and <b>Minimized</b> properties, and their associated accessor methods. In this case, use the internal <code>FrameProxy</code> which has always contained them:</p>
<pre lang='matlab'>
>> jFrameProxy = jFrame.fFigureClient.getWindow()
jFrameProxy =
com.mathworks.hg.peer.FigureFrameProxy$FigureFrame[fClientProxyFrame,227,25,568x502,invalid,layout=java.awt.BorderLayout,title=Figure 1,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,...]
>> % Three alternative possibilities of setting Minimized:
>> jFrameProxy.setMinimized(true);
>> set(jFrameProxy,'Minimized',true);
>> jFrameProxy.handle.Minimized = true;
</pre>
<p>Using <code>FrameProxy</code> for figure minimization and maximization works correctly on both old and new Matlab releases; using <code>jFrame</code> is slightly simpler but only works on recent Matlab releases. Depending on your needs you may choose to use either of these. They are entirely equivalent.<br />
When either the <b>Maximized</b> or <b>Minimized</b> properties are changed back to false, the window is restored to regular mode, which is the <code>FrameProxy</code>&#8216;s <b>RestoredLocation</b> and <b>RestoredSize</b>.</p>
<h3 id="JavaFrame">Use of the JavaFrame property</h3>
<p>Note that all this relies on the undocumented hidden figure property <b>JavaFrame</b>, which issues a standing warning (since Matlab release R2008a) of becoming obsolete in some future Matlab release (HG2?):</p>
<div class="wp_syntax">
<div class="code">
<pre style="font-family: monospace;"><span style="color: #000000;">>> jFrame = </span><span style="color: #0000ff;">get</span>(<span style="color: #0000ff;">gcf</span>,<span style="color: #800080;">'JavaFrame'</span>)
<span style="color: #ff0000;">Warning: figure JavaFrame property will be obsoleted in a future release.</span>
<span style="color: #000000;">For more information see the JavaFrame resource on the MathWorks web site.
(Type "warning off MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame" to suppress this warning.)
jFrame =
com.mathworks.hg.peer.FigurePeer@1ffbad6</span>
</pre>
</div>
</div>
<p>To remove the above warning I have used (note the <i><b>handle</b></i> wrapper, as <a target="_blank" href="/articles/detecting-window-focus-events/#comment-2756">suggested</a> by Donn Shull):</p>
<pre lang="matlab">jFrame = get(handle(gcf),'JavaFrame')</pre>
<p>If and when <b>JavaFrame</b> does become obsolete in some future Matlab version, be sure to look in this blog for workarounds.<br />
You may also wish to inform MathWorks on the dedicated webpage that they have set up for specifically this reason (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/javaframe">http://www.mathworks.com/javaframe</a>), how you are using <b>JavaFrame</b> and why it is important for you. This may help them to decide whether to keep <b>JavaFrame</b> or possibly add the functionality using other means.<br />
Do you have a smart use for the figure&#8217;s minimization or maximization feature? or another use for <b>JavaFrame</b>? If so, please share your ideas in a <a target="_blank" href="/articles/minimize-maximize-figure-window#respond">comment</a> below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/minimize-maximize-figure-window">Minimize/maximize figure window</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/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/disable-entire-figure-window" rel="bookmark" title="Enable/disable entire figure window">Enable/disable entire figure window </a> <small>Disabling/enabling an entire figure window is impossible with pure Matlab, but is very simple using the underlying Java. This article explains how....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/minimize-maximize-figure-window/feed</wfw:commentRss>
			<slash:comments>52</slash:comments>
		
		
			</item>
		<item>
		<title>UDD and Java</title>
		<link>https://undocumentedmatlab.com/articles/udd-and-java?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=udd-and-java</link>
					<comments>https://undocumentedmatlab.com/articles/udd-and-java#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 23 Mar 2011 21:04:35 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[Listener]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2213</guid>

					<description><![CDATA[<p>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/udd-and-java">UDD and Java</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-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>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface" rel="bookmark" title="JMI &#8211; Java-to-Matlab Interface">JMI &#8211; Java-to-Matlab Interface </a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/extending-a-java-class-with-udd" rel="bookmark" title="Extending a Java class with UDD">Extending a Java class with UDD </a> <small>Java classes can easily be extended in Matlab, using pure Matlab code. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I welcome Donn Shull, who concludes his series on Matlab&#8217;s undocumented UDD mechanism with a discussion of the UDD-Java relationship.</i></p>
<h3 id="Introduction">Introduction to the UDD-Java relationship</h3>
<p>Over the course of this series we have mentioned connections between UDD and Java. In <a target="_blank" href="/articles/udd-events-and-listeners/">UDD Events and Listeners</a> we described how in Matlab each Java object can have a UDD companion. In <a target="_blank" href="/articles/hierarchical-systems-with-udd/">Hierarchical Systems with UDD</a> we briefly noted that a UDD hierarchy may be passed to Java. This suggests that there is a two way relationship between between UDD and Java.<br />
In this article we will use some undocumented built-in methods such as <b><i>java</i></b> and <b><i>classhandle</i></b> to explore the UDD-Java relationship. We have used built-in methods for UDD objects before. We have also mentioned the importance of studying code from The MathWorks. When you come across something that looks like it may be a UDD method you can check with the <b><i>which</i></b> command:</p>
<pre lang="matlab">
>> which java -all
C:\MATLAB\R2010b\toolbox\matlab\general\java.m
java is a built-in method                               % javahandle.com.mathworks.hg.peer.Echo method
java is a built-in method                               % ui.figure method
java is a built-in method                               % hg2utils.HGHandle method
java is a built-in method                               % JavaVisible method
java is a built-in method                               % hg.figure method
java is a built-in method                               % hg.GObject method
java is a built-in method                               % schema.class method
java is a built-in method                               % handle.handle method
java is a built-in method                               % schema.method method
C:\MATLAB\R2010b\toolbox\rptgen\rptgen\@sgmltag\java.m  % sgmltag method
</pre>
<p>If you find <code>schema.class</code> in the comments for built-in methods, then the method is a general UDD method.</p>
<h3 id="javahandle">UDD javahandle companions for Java object</h3>
<p>Whenever a Java class is instantiated in Matlab, it is possible to <a target="_blank" href="/articles/udd-events-and-listeners/#Java">create a companion UDD object</a>. The created companion can be in either the <code>javahandle</code> or the <code>javahandle_withcallbacks</code> package. The primary reason for creating the companion object is to avoid <a rel="nofollow" target="_blank" href="http://mathforum.org/kb/message.jspa?messageID=5950839">memory leaks</a> when attaching a Matlab callback to a callback property. It makes sense in general to use the <code>javahandle_withcallbacks</code> package.</p>
<pre lang="matlab">
>> % creage a java instance and the companion UDD object
>> javaFrame = javax.swing.JFrame;
>> % dot notation
>> javaFrameUDD = javaFrame.handle('CallbackProperties');
>> % or Matlab notation
>> javaFrameUDD = handle(javaFrame,'CallbackProperties');
</pre>
<p>We can use the built-in <b><i>classhandle</i></b> method to inspect our UDD companion object. This can be used, for example, to obtain a list of the events that the Java class generates:</p>
<pre lang="matlab">
>> % use classhandle to list a java classes events
>> jch = javaFrame.handle.classhandle;
>> for index = 1:numel(jch.Events), disp(jch.Events(index).Name); end
MouseWheelMoved
MouseClicked
MouseEntered
MouseExited
MousePressed
MouseReleased
WindowGainedFocus
WindowLostFocus
WindowActivated
WindowClosed
WindowClosing
WindowDeactivated
WindowDeiconified
WindowIconified
WindowOpened
ComponentHidden
ComponentMoved
ComponentResized
ComponentShown
MouseDragged
MouseMoved
ComponentAdded
ComponentRemoved
AncestorMoved
AncestorResized
FocusGained
FocusLost
WindowStateChanged
HierarchyChanged
CaretPositionChanged
InputMethodTextChanged
PropertyChange
KeyPressed
KeyReleased
KeyTyped
>> % Use one of the object's callbacks
>> set(javaFrameUDD,'WindowGainedFocusCallback',@myCallbackFcn);
</pre>
<p>If we do not wish to use callback properties, then we can create our UDD companion in the <code>javahandle</code> package and use <b><i>handle.listener</i></b> to respond to events.</p>
<pre lang="matlab">
javaFrame = javax.swing.JFrame;
javaFrameUDD = javaFrame.handle;
lis = handle.listener(javaFrameUDD,'WindowGainedFocus',@myCallbackFcn);
</pre>
<h3 id="Passing">Passing UDD objects to Java code</h3>
<p>You can pass any UDD object to your Java classes in Matlab. Matlab will create a Java bean adapter for the UDD object. The bean adapter created is a subclass of <code>com.MathWorks.jmi.bean.UDDObject</code>. <code>UDDObject</code> implements the Java interfaces <code>com.MathWorks.jmi.bean.DynamicProperties</code>, <code>com.MathWorks.jmi.bean.MTObject</code>, <code>com.MathWorks.jmi.bean.TreeObject</code>, and <code>com.mathworks.services.Browseable</code>.<br />
The generated bean adapter will have the methods of the parent class the methods of the UDD class, as well as <i>set</i> and <i>get</i> methods for the class properties. To understand how this works, let&#8217;s start with our <code>simple.object</code> and use the <b><i>java</i></b> method to inspect the bean adapter:</p>
<pre lang="matlab">
>> myObj = simple.object('myObj', 2);
>> % using dot notation with the java method
>> myObj.java.getClass
ans =
class objectBeanAdapter0
>> myObj.java.methods
Methods for class objectBeanAdapter0:
acquireReference                    createNullMatlabObjectListener      lastDown
addBelow                            createNullPropertyChangeListener    left
addBrowseableListener               dialog                              notify
addFirstBelow                       disp                                notifyAll
addLeft                             dispose                             objectBeanAdapter0
addMatlabObjectListener             equals                              releaseReference
addObjectPropertyChangeListener     findProperty                        removeBrowseableListener
addRight                            firstDown                           removeMatlabObjectListener
browseableCanHaveChildren           getChildAt                          removeObjectPropertyChangeListener
browseableChild                     getChildCount                       right
browseableChildCount                getClass                            setDirtyFlag
browseableChildFetchCount           getClassName                        setDynamicPropertyValue
browseableChildren                  getDynamicProperties                setName
browseableDataObject                getDynamicPropertyValue             setPropertyValue
browseableDisplayObject             getIndex                            setThreadSafetyCheckLevel
browseableHasChildren               getIndexOfChild                     setValue
browseableNChildren                 getName                             toString
browseableNextNSiblings             getNewInstance                      up
browseableNextSibling               getPropertyValue                    updateCache
browseableParent                    getValue                            updateChildCount
browseablePrevNSiblings             hashCode                            updateIndex
browseablePrevSibling               isDirty                             wait
checkThreadSafety                   isLeaf
clearDirtyFlag                      isObservable
compareTo                           isValid
</pre>
<p>The parent class has added a large number of methods to the bean adapter for our original class. By looking at the list we can see our <i>dialog</i> and <i>disp</i> methods. There are also <i>getName</i>, <i>setName</i>, <i>getValue</i>, and <i>setValue</i> methods for our classes properties. The rest of the methods were inherited from the base <code>UDDObject</code> superclass. We can use any superclass method directly with the bean adapter object. For example:</p>
<pre lang="matlab">
>> myObj.java.getPropertyValue('Name')
ans =
myObj
</pre>
<h3 id="Interface">Java interface class</h3>
<p>To be able to use our UDD object in user-written Java code, we need a Java interface class for it. While we could manually write an interface file, UDD provides a very handy convenience method to automatically create the interface file. For this, we use the <b><i>classhandle</i></b> method again. The <code>schema.class</code> object obtained using <b><i>classhandle</i></b> has a method called <i>createJavaInterface</i> that takes two string arguments: the Java interface classname, and the folder in which to place the interface file. The steps to create and use this interface file are:</p>
<ol>
<li>Create and test your UDD class</li>
<li>Create a Java interface file using <code>schema.class</code>&#8216;s <i>CreateJavaInterface</i></li>
<li>Modify your UDD class definition file (schema.m) to reference the Java interface file</li>
<li>Create the Java code that uses your class</li>
</ol>
<p>For example, to create a Java interface file for the simple object we created above, use the following commands in Matlab:</p>
<pre lang="matlab">
classH = classhandle(myObj);
classH.createJavaInterface('simpleObjectInterface',pwd);
</pre>
<p>This will create the following simpleObjectInterface.java file in the current working directory:</p>
<pre lang="java">
public interface simpleObjectInterface
       extends com.mathworks.jmi.bean.TreeObject
{
    /* Properties */
    public java.lang.String getName();
    public void setName(java.lang.String value);
    public double getValue();
    public void setValue(double value);
    /* Methods */
    public void dialog();
    public void disp();
}
</pre>
<p>The interface file contains <i>set</i> and <i>get</i> accessor methods for our UDD object properties, and Java prototypes for the UDD methods (in our case, <i>dialog</i> and <i>disp</i>).<br />
The next step is to modify our class definition file (schema.m) to reference the Java interface file we have created. This modification provides the information that Matlab needs to create the bean adapter that implements the Java interface:</p>
<pre lang="matlab">
simpleClass = schema.class(simplePackage, 'object');
simpleClass.JavaInterfaces = { 'simpleObjectInterface' };
</pre>
<p>We can verify that the generated bean adapter implements the interface using Java Reflection techniques. As always when we have made changes to the class definition file, we need to use the <b><i>clear classes</i></b> command, and then recreate our objects:</p>
<pre lang="matlab">
>> myObj = simple.object('myObj', pi)
myObj =
  Name: myObj
 Value: 3.141593
>> myObjBean = java(myObj)
myObjBean =
  Name: myObj
 Value: 3.141593
>> interfaces = myObjBean.getClass.getInterfaces
interfaces =
java.lang.Class[]:
    [java.lang.Class]
>> interfaces(1)
ans =
interface simpleObjectInterface
</pre>
<h3 id="Usage">Using UDD in Java</h3>
<p>Let&#8217;s create a simple Java class that illustrates passing a UDD object to Java. Here we will just have two methods: The first gets the Value property from a class instance and doubles it; the second launches the class instance dialog:</p>
<pre lang="java">
public class accessUDDClass
{
  double localValue;
  public void accessUDDClass() {
  }
  public void doubleValue(simpleObjectInterface UDDObj) {
    localValue = UDDObj.getValue();
    UDDObj.setValue(2*localValue);
  }
  public void launchDialog(simpleObjectInterface UDDObj) {
    UDDObj.dialog();
  }
}
</pre>
<p>If we have set up the Java compiler and environment variables correctly, we can compile our interface and Java class files from inside Matlab using the system command (alternately, we can compile using any external Java compiler or IDE):</p>
<pre lang="matlab">
>> system('javac accessUDDClass.java simpleObjectInterface.java')
ans =
     0
</pre>
<p>Now test our simple Java class with the UDD object created earlier:</p>
<pre lang="matlab">
>> javaObj = accessUDDClass
javaObj =
accessUDDClass@eb9b73
>> javaObj.doubleValue(myObj)  % pi => 2*pi
>> myObj
myObj =
  Name: myObj
 Value: 6.283185
</pre>
<p>This concludes the UDD series. I would like to thank Yair for his help in preparing and presenting this information.</p>
<h3 id="Editor">Editor&#8217;s note</h3>
<p><i>I would like to thank Donn for his enourmously detailed work on UDD, and for preparing it in easy-to-follow articles. I can personally attest to the huge time investment it has taken him. I trully believe he deserves a warm &#8220;thank you&#8221; from the Matlab community. Please visit <a target="_blank" rel="nofollow" href="http://aetoolbox.com/default.aspx">Donn&#8217;s website</a>, or add a short <a href="/articles/udd-and-java/#respond">comment</a> below.<br />
In the following weeks, I return to the regular stuff that made this website famous: solving day-to-day Matlab problems using simple undocumented built-in Matlab gems.<br />&#8211; Yair</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/udd-and-java">UDD and Java</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-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>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface" rel="bookmark" title="JMI &#8211; Java-to-Matlab Interface">JMI &#8211; Java-to-Matlab Interface </a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/extending-a-java-class-with-udd" rel="bookmark" title="Extending a Java class with UDD">Extending a Java class with UDD </a> <small>Java classes can easily be extended in Matlab, using pure Matlab code. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/udd-and-java/feed</wfw:commentRss>
			<slash:comments>4</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 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>
		<item>
		<title>Hierarchical Systems with UDD</title>
		<link>https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hierarchical-systems-with-udd</link>
					<comments>https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Mar 2011 18:00:25 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Handle graphics]]></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[JMI]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[schema.prop]]></category>
		<category><![CDATA[uitools]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2146</guid>

					<description><![CDATA[<p>UDD objects can be grouped in structured hierarchies - this article explains how</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd">Hierarchical Systems with UDD</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/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/introduction-to-udd" rel="bookmark" title="Introduction to UDD">Introduction to UDD </a> <small>UDD classes underlie many of Matlab's handle-graphics objects and functionality. This article introduces these classes....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</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><i>Once again I welcome guest blogger <a target="_blank" rel="nofollow" href="http://aetoolbox.com/">Donn Shull</a>, who continues his multi-part series about Matlab’s undocumented UDD objects.</i><br />
We have looked at the <a target="_blank" href="/articles/introduction-to-udd/">tools for working with UDD classes</a>, and <a target="_blank" href="/articles/creating-a-simple-udd-class/">created a simple UDD class</a>. Today I shall show how to create a hierarchy of UDD objects.</p>
<h3 id="hierarchy">Creating hierarchical structures with UDD objects</h3>
<p>UDD is the foundation for both Handle Graphics (HG) and Simulink. Both are hierarchical systems. It stands to reason that UDD would offer support for hierarchical structures. It is straightforward to connect UDD objects together into searchable tree structures. All that is necessary is a collection of UDD objects that don&#8217;t have any methods or properties named <code>'connect', 'disconnect', 'up', 'down', 'left', 'right'</code> or <code>'find'</code>.<br />
We illustrate the technique by creating a hierarchy of <code>simple.object</code>s as shown in the following diagram:<br />
<center><figure style="width: 200px" class="wp-caption aligncenter"><img decoding="async" alt="Sample UDD objects hierarchy" src="https://undocumentedmatlab.com/images/UDD_structure.png" title="Sample UDD objects hierarchy" width="200" height="177" /><figcaption class="wp-caption-text">Sample UDD objects hierarchy</figcaption></figure></center><br />
To begin we create five instances of the <code>simple.object</code> class from the previous article:</p>
<pre lang="matlab">
% Remember that simple.object accepts a name and a value
a = simple.object('a', 1);
b = simple.object('b', 1);
c = simple.object('c', 0);
d = simple.object('d', 1);
e = simple.object('e', 1);
</pre>
<p>To form the structure we use the <i>connect</i> method. We can use either dot notation or the Matlab syntax:</p>
<pre lang="matlab">
% Dot-notation examples:
a.connect(b, 'down');
b.connect(a, 'up');       % alternative to the above
% Matlab notation examples:
connect(a, b, 'down');
connect(b, a, 'up');      % alternative to the above
</pre>
<p>Next, connect node c into our hierarchy. There are several options here: We can use &#8216;down&#8217; to connect a to c. Or we could use &#8216;up&#8217; to connect c to a. Similarly, we can use either &#8216;left&#8217; or &#8216;right&#8217; to connect b and c. Here&#8217;s one of the many possible ways to create our entire hierarchy:</p>
<pre lang="matlab">
b.connect(a, 'up');
c.connect(b, 'left');
d.connect(b, 'up');
e.connect(d, 'left');
</pre>
<h3 id="inspecting">Inspecting UDD hierarchy structures</h3>
<p>We now have our structure and each object knows its connection to other objects. For example, we can inspect b&#8217;s connections as follows:</p>
<pre lang="matlab">
>> b.up
ans =
  Name: a
 Value: 1.000000
>> b.right
ans =
  Name: c
 Value: 0.000000
>> b.down
ans =
  Name: d
 Value: 1.000000
</pre>
<p>We can search our structure by using an undocumented form of the built-in <i><b>find</b></i> command. When used with connected UDD structures, <i><b>find</b></i> can be used in the following form:</p>
<pre lang="matlab">objectArray = find(startingNode, 'property', 'value', ...)</pre>
<p>To search from the top of our hierarchy for objects of type <code>simple.object</code> we would use:</p>
<pre lang="matlab">
>> find(a, '-isa', 'simple.object')
ans =
        simple.object: 5-by-1    % a, b, c, d, e
</pre>
<p>Which returns all the objects in our structure, since all of them are <code>simple.object</code>s. If we repeat that command starting at b we would get:</p>
<pre lang="matlab">
>> find(b, '-isa', 'simple.object')
ans =
	simple.object: 3-by-1    % b, d, e
</pre>
<p><i><b>find</b></i> searches the structure downward from the current node. Like many Matlab functions, <i><b>find</b></i> can be used with multiple property value pairs, so if we want to find <code>simple.object</code> objects in our structure with <b>Value</b> property =0, we would use the command:</p>
<pre lang="matlab">
>> find(a, '-isa', 'simple.object', 'Value', 0)
ans =
  Name: c
 Value: 0.000000
</pre>
<h3 id="visualizing">Visualizing a UDD hierarchy</h3>
<p>Hierarchical structures are also known as tree structures. Matlab has an undocumented function for visualizing and working with trees namely <i><b>uitree</b></i>. Yair has described <i><b>uitree</b></i> in a <a target="_blank" href="/articles/uitree/">series of articles</a>. Rather than following the techniques in shown in Yair&#8217;s articles, we are going to use a different method that will allow us to introduce the following important techniques for working with UDD objects:</p>
<ul>
<li>Subclassing, building your class on the foundation of a parent class</li>
<li>Overloading properties and methods of the superclass</li>
<li>Using meta-properties <b>GetfFunction</b> and <b>SetFunction</b></li>
</ul>
<p>Because the steps shown below will subclass an HG class, they will modify our <code>simple.object</code> class and probably make it unsuitable for general use. Yair has shown that <i><b>uitree</b></i> is ready made for displaying HG trees and we saw above that HG is a UDD system. We will use the technique from <code>uitools.uibuttongroup</code> to make our <code>simple.object</code> class a subclass of the HG class <code>hg.uipanel</code>. Modify the class definition file as follows:</p>
<pre lang="matlab">
% class definition
superPackage = findpackage('hg');
superClass = findclass(superPackage, 'uipanel');
simpleClass = schema.class(simplePackage, 'object',superClass);
</pre>
<p>Now we can either issue the <i><b>clear classes</b></i> command or restart Matlab and then recreate our structure. The first thing that you will notice is that when we create the first <code>simple.object</code> that a figure is also created. This is expected and is the reason that this technique is not useful in general. We will however use this figure to display our structure with the following commands:</p>
<pre lang="matlab">
t = uitree('v0', 'root', a);  drawnow;
t.expand(t.getRoot);  drawnow;
t.expand(t.getRoot.getFirstChild);
</pre>
<p><center><figure style="width: 441px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Simple structure presented in a Matlab uitree" src="https://undocumentedmatlab.com/images/UDD_uitree_1.png" title="Simple structure presented in a Matlab uitree" width="441" height="189" /><figcaption class="wp-caption-text">Simple structure presented in a Matlab <i><b>uitree</b></i></figcaption></figure></center><br />
The label on each of our objects is &#8216;uipanel&#8217; and this is probably not what we want. If we inspect our object or its <code>hg.uipanel</code> super-class (note: this would be a great time to use Yair&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object"><i><b>uiinspect</b></i> utility</a>), we can see there is a <b>Type</b> property that has a value of &#8216;uipanel&#8217;. Unfortunately this property is read-only, so we cannot change it. We can however overload it by placing a <i><b>schema.prop</b></i> in our class definition named <b>Type</b>. This will allow us to overload or replace the parent&#8217;s <b>Type</b> property with our own definition:</p>
<pre lang="matlab">
p = schema.prop(simpleClass, 'Type', 'string');
p.FactoryValue = 'simple.object';
</pre>
<p>Once again, issue the <i><b>clear classes</b></i> command or restart Matlab, then recreate our structure. Our tree now has each node labeled with the &#8216;simple.object&#8217; label:<br />
<center><figure style="width: 441px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Corrected node names for our UDD structure" src="https://undocumentedmatlab.com/images/UDD_uitree_2.png" title="Corrected node names for our UDD structure" width="441" height="189" /><figcaption class="wp-caption-text">Corrected node names for our UDD structure</figcaption></figure></center><br />
This is a little more descriptive but what would really be nice is if we could label each node with the value of the <b>Name</b> property. As luck would have it, we can do just that. When we add a property to a UDD class we are adding an object of type <code>schema.prop</code>. So our properties have their own properties and methods (so-called <i>meta-data</i>). We are going to set the <b>GetFunction</b> property of our <b>Type</b> property. <b>GetFunction</b> holds a handle of the function to be called whenever the property is accessed:</p>
<pre lang="matlab">
p = schema.prop(simpleClass, 'Type', 'string');
p.GetFunction = @getType;
</pre>
<p>The prototype for the function that <b>GetFunction</b> references has three inputs and one output: The inputs are the handle of the object possessing the property, the value of that property, and the property object. The output is the value that will be supplied when the property is accessed. So our <b>GetFunction</b> can be written to supply the value of the <b>Name</b> property whenever the <b>Type</b> property value is being read:</p>
<pre lang="matlab">
function propVal = getType(self, value, prop)
   propVal = self.Name;
end
</pre>
<p>Alternately, as a single one-liner in the schema definition file:</p>
<pre lang="matlab">p.GetFunction = @(self,value,prop) self.Name;</pre>
<p>Similarly, there is a corresponding <b>SetFunction</b> that enables us to intercept changes to a property&#8217;s value and possibly disallow invalid values.<br />
With these changes when we recreate our <i><b>uitree</b></i> we obtain:<br />
<center><figure style="width: 441px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Overloaded property GetFunction" src="https://undocumentedmatlab.com/images/UDD_uitree_3.png" title="Overloaded property GetFunction" width="441" height="189" /><figcaption class="wp-caption-text">Overloaded property <b>GetFunction</b></figcaption></figure></center></p>
<h3 id="java">A Java class for UDD trees</h3>
<p>We will have more to say about the relationship between UDD and Java in a future article. For now we simply note that the <code>com.mathworks.jmi.bean.UDDObjectTreeModel</code> class in the <a target="_blank" href="/articles/jmi-java-to-matlab-interface/">JMI package</a> provides some UDD tree navigation helper functions. Methods include <i>getChild, getChildCount, getIndexOfChild</i> and <i>getPathToRoot</i>. The <code>UDDObjectTreeModel</code> constructor requires one argument, an instance of your UDD tree root node:</p>
<pre lang="matlab">
% Create a UDD tree-model instance
>> uddTreeModel = com.mathworks.jmi.bean.UDDObjectTreeModel(a);
% Get index of child e and its parent b:
>> childIndex = uddTreeModel.getIndexOfChild(b, e)
childIndex =
     1
% Get the root's first child (#0):
>> child0 = uddTreeModel.getChild(a, 0)
child0 =
  Name: b
 Value: 1.000000
% Get the path from node e to the root:
>> path2root = uddTreeModel.getPathToRoot(e)
path2root =
com.mathworks.jmi.bean.UDDObject[]:
    [simple_objectBeanAdapter2]      % <= a
    [simple_objectBeanAdapter2]      % <= b
    [simple_objectBeanAdapter2]      % <= e
>> path2root(3)
ans =
  Name: e
 Value: 1.000000
</pre>
<p>We touched on a few of the things that you can do by modifying the properties of a <code>schema.prop</code> in this article. In the following article we will take a more detailed look at this essential class.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd">Hierarchical Systems with UDD</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/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/introduction-to-udd" rel="bookmark" title="Introduction to UDD">Introduction to UDD </a> <small>UDD classes underlie many of Matlab's handle-graphics objects and functionality. This article introduces these classes....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</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/hierarchical-systems-with-udd/feed</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<item>
		<title>Creating a simple UDD class</title>
		<link>https://undocumentedmatlab.com/articles/creating-a-simple-udd-class?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=creating-a-simple-udd-class</link>
					<comments>https://undocumentedmatlab.com/articles/creating-a-simple-udd-class#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 23 Feb 2011 17:29:05 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[schema.class]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2130</guid>

					<description><![CDATA[<p>This article explains how to create and test custom UDD packages, classes and objects</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class">Creating a simple UDD class</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/extending-a-java-class-with-udd" rel="bookmark" title="Extending a Java class with UDD">Extending a Java class with UDD </a> <small>Java classes can easily be extended in Matlab, using pure Matlab code. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/simple-gui-tabs-for-advanced-matlab-trading-app" rel="bookmark" title="Simple GUI Tabs for Advanced Matlab Trading App">Simple GUI Tabs for Advanced Matlab Trading App </a> <small>A new File Exchange utility enables to easily design GUI tabs using Matlab's GUIDE...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I welcome guest blogger <a target="_blank" rel="nofollow" href="http://aetoolbox.com/">Donn Shull</a>, who continues his multi-part series about Matlab&#8217;s undocumented UDD objects.</i></p>
<h3 id="package">Creating a new UDD package</h3>
<p>To illustrate the construction of UDD classes with Matlab m-code, let&#8217;s create a simple class belonging to a new simple package. Our class will have two properties: a <b>Name</b> property of type string, and a <b>Value</b> property of type double. This class will have two methods that will illustrate overloading the built-in <i><b>disp</b></i> function, and using a <i>dialog</i> method to present a GUI. Our class will also have one event, to demonstrate UDD event handling.<br />
To create this simple UDD class we need two directories and five m-files (downloadable <a href="/files/simple.zip">here</a>): The parent directory needs to be a directory on the Matlab path. A subdirectory of the parent directory is named with the symbol @ followed by our UDD package name &#8211; this is the package directory. In this example, the subdirectory is called @simple.<br />
Within the @simple directory, place a file named <i>schema.m</i>, which is the package definition file. This is a very simple file, that merely calls <i><b>schema.package</b></i> to create a new package called &#8216;simple&#8217;:</p>
<pre lang="matlab">
function schema()
%SCHEMA simple package definition function.
   schema.package('simple');
end
</pre>
<p>If you place additional m-files in the package directory they will be called package function files. Those files will have package scope and can be accessed with the notation <code>packagename.functionname</code>. We will not use package functions in this example, so we will only have the schema.m file shown above.</p>
<h3 id="class">Creating a new UDD class</h3>
<p>Next, create another subdirectory beneath @simple, named with an @ symbol followed by the UDD class name. In this example we will create the directory @object (i.e., /@simple/@object/). We place four m-files in this directory:<br />
The first file is yet another schema.m file, which is the class-definition file:</p>
<pre lang="matlab">
function schema()
%SCHEMA  simple.object class definition function.
   % Get a handle to the 'simple' package
   simplePackage = findpackage('simple');
   % Create a base UDD object
   simpleClass = schema.class(simplePackage, 'object');
   % Define the class methods:
   % dialog.m method
   m = schema.method(simpleClass, 'dialog');
   s = m.Signature;
   s.varargin    = 'off';
   s.InputTypes  = {'handle'};
   s.OutputTypes = {};
   % disp.m method
   m = schema.method(simpleClass, 'disp');
   s = m.Signature;
   s.varargin    = 'off';
   s.InputTypes  = {'handle'};
   s.OutputTypes = {};
   % Define the class properties:
   schema.prop(simpleClass, 'Name', 'string');
   schema.prop(simpleClass, 'Value', 'double');
   % Define the class events:
   schema.event(simpleClass, 'simpleEvent');
end
</pre>
<p>Here, we used the built-in <i><b>findpackage</b></i> function to identify our base package (<code>simple</code>). Then we used <i><b>schema.class</b></i> to define a new class &#8216;object&#8217; within that base package. We next defined two class methods, two properties and finally an event.</p>
<h3 id="methods">Defining class methods</h3>
<p>It is not mandatory to define the method signatures as we have done in our class definition file. If you omit the method signature definitions, Matlab will automatically generate default signatures that will actually work in most applications. However, I believe that it is bad practice to omit the method signature definitions in a class definition file, and there are cases where your classes will not work as you have intended if you omit them.<br />
Now, place a file named object.m in the @object directory. This file contains the class constructor method, which is executed whenever a new instance object of the <code>simple.object</code> class is created:</p>
<pre lang="matlab">
function simpleObject = object()
%OBJECT constructor for the simple.object class
%
%   SIMPLEOBJECT = OBJECT(NAME, VALUE) creates an instance of the
%   simple.object class with the Name property set to NAME and the
%   Value property set VALUE
%
%   SIMPLEOBJECT = OBJECT(NAME) creates an instance of the simple.object
%   class with the Name property set to NAME. The Value property will be
%   given the default value of 0.
%
%   SIMPLEOBJECT = OBJECT creates an instance of the simple.object class
%   and executes the simple.object dialog method to open a GUI for editing
%   the Name and Value properties.
%
%   INPUTS:
%       NAME          : string
%       VALUE         : double
%
%   OUTPUTS:
%       SIMPLEOBJECT  : simple.object instance
   simpleObject = simple.object;
   switch nargin
      case 0
         simpleObject.dialog;
      case 1
         simpleObject.Name = name;
      case 2
         simpleObject.Name = name;
         simpleObject.Value = value;
   end
end
</pre>
<p>The two other m-files in the @object directory will be our class methods &#8211; a single file for each method. In our case they are disp.m and dialog.m:</p>
<pre lang="matlab">
function disp(self)
%DISP overloaded object disp method
%
%   DISP(SELF) or SELF.DISP uses the MATLAB builtin DISP function
%   to display the Name and Value properties of the object.
%
%   INPUTS:
%       SELF  : simple.object instance
   builtin('disp', sprintf('  Name: %s\n Value: %f', self.Name, self.Value));
   %Alternative: fprintf('\n  Name: %s\n Value: %f', self.Name, self.Value));
end
</pre>
<p>And the dialog method (in dialog.m):</p>
<pre lang="matlab">
function dialog(self)
%DIALOG dialog method for simple.object for use by openvar
%
%   DIALOG(SELF) or SELF.DIALOG where self is the name of the simple.object
%   instance opens a gui to edit the Name and Value properties of self.
%
%   INPUTS:
%       SELF  : simple.object
   dlgValues = inputdlg({'Name:', 'Value:'}, 'simple.object', 1, {self.Name, mat2str(self.Value)});
   if ~isempty(dlgValues)
      self.Name = dlgValues{1};
      self.Value = eval(dlgValues{2});
   end
end
</pre>
<h3 id="testing">Testing our new class</h3>
<p>Now let&#8217;s test our new class by creating an instance without using any input arguments</p>
<pre lang="matlab">a = simple.object</pre>
<p>This calls the object&#8217;s constructor method, which launches the input dialog GUI:<br />
<center><figure style="width: 181px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="UDD simple class GUI" src="https://undocumentedmatlab.com/images/UDD_simple_object_1.jpg" title="UDD simple class GUI" width="181" height="163" /><figcaption class="wp-caption-text">UDD simple class GUI</figcaption></figure></center><br />
Note the default empty string value for the <b>Name</b> property, and the default zero value for the <b>Value</b> property. In one of the following articles I will show how to control property values. For now let&#8217;s assign &#8216;a&#8217; to <b>Name</b> and 1 to <b>Value</b> using the GUI. Selecting OK updates our object and closes the GUI. Matlab then calls the object&#8217;s <i>disp</i> method to display our object in the command window:</p>
<pre lang="matlab">
a =
  Name: a
 Value: 1.000000
</pre>
<p>We can reopen our object&#8217;s GUI using three methods: The most obvious is to invoke the <i>dialog</i> method using <code>a.dialog</code> or <code>dialog(a)</code>. Alternately, double click on a in the workspace explorer window &#8211; Matlab will automatically call the built-in <i><b>openvar</b></i> function with the variable name and value as arguments. Which leads us to the third method &#8211; simply call <i><b>openvar</b>(&#8216;a&#8217;, a)</i> directly:</p>
<pre lang="matlab">
% Alternatives for programmatically displaying the GUI
a.dialog();  % or simply: a.dialog
dialog(a);
openvar('a',a);
</pre>
<h3 id="help">Accessing UDD help</h3>
<p>You may have noticed that in our constructor and method files we have included help text. This is good practice for all Matlab files in general, and UDD is no exception. We can access the UDD class help as follows:</p>
<pre lang="text">
> help simple.object
 OBJECT constructor for the simple.object class
    SIMPLEOBJECT = OBJECT(NAME, VALUE) creates an instance of the
    simple.object class with the Name property set to NAME and the
    Value property set VALUE
    SIMPLEOBJECT = OBJECT(NAME) creates an instance of the simple.object
    class with the Name property set to NAME. The Value property will be
    given the default value of 0.
    SIMPLEOBJECT = OBJECT creates an instance of the simple.object class
    and executes the simple.object dialog method to open a GUI for editing
    the Name and Value properties.
    INPUTS:
        NAME          : string
        VALUE         : double
    OUTPUTS:
        SIMPLEOBJECT  : simple.object instance
>> help simple.object.disp
 DISP overloaded object disp method
    DISP(SELF) or SELF.DISP uses the MATLAB builtin DISP function
    to display the Name and Value properties of the object.
    INPUTS:
        SELF  : simple.object instance
</pre>
<p>One of the best ways to learn how Matlab works is to examine code written by the Matlab development team. <i><b>openvar</b></i> is a good example: By looking at it we can see that if a variable is a <i><b>handle</b></i> object and is opaque, then <i><b>openvar</b></i> will check to see if it has a <i>dialog</i> method. If so, it will use that to open the variable for editing. With this information we can guess that MCOS, UDD and even java objects can all launch their own dialog editors simply by having an appropriate <i>dialog</i> method.<br />
An excellent source of UDD information is available in the Matlab toolbox folders. The base Matlab toolbox contains sixteen different UDD packages to explore. Yummy!<br />
In the next article of this UDD series we will look at creating hierarchical structures using our <code>simple.object</code> and a unique UDD method.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class">Creating a simple UDD class</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/extending-a-java-class-with-udd" rel="bookmark" title="Extending a Java class with UDD">Extending a Java class with UDD </a> <small>Java classes can easily be extended in Matlab, using pure Matlab code. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/simple-gui-tabs-for-advanced-matlab-trading-app" rel="bookmark" title="Simple GUI Tabs for Advanced Matlab Trading App">Simple GUI Tabs for Advanced Matlab Trading App </a> <small>A new File Exchange utility enables to easily design GUI tabs using Matlab's GUIDE...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/creating-a-simple-udd-class/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Introduction to UDD</title>
		<link>https://undocumentedmatlab.com/articles/introduction-to-udd?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=introduction-to-udd</link>
					<comments>https://undocumentedmatlab.com/articles/introduction-to-udd#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 16 Feb 2011 18:00:09 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[schema.class]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2036</guid>

					<description><![CDATA[<p>UDD classes underlie many of Matlab's handle-graphics objects and functionality. This article introduces these classes.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/introduction-to-udd">Introduction to UDD</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-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>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
<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/new-information-on-hg2" rel="bookmark" title="New information on HG2">New information on HG2 </a> <small>More information on Matlab's new HG2 object-oriented handle-graphics system...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://aetoolbox.com/">Donn Shull</a>. Donn will present a series of articles about UDD classes and objects, on which many undocumented Matlab features and functions are based.</i></p>
<h3 id="Background">Background on UDD</h3>
<p>Matlab has used objects for a long time. In R8 (Matlab 5.0), their first user accessible class system was introduced. Andy Register wrote a <a target="_blank" rel="nofollow" href="http://www.scitechpub.com/catalog/product_info.php?products_id=386">detailed reference</a> on using this system. Although that original system is obsolete, it is still available in R24 (R2010b).<br />
UDD objects (also referred to as <i>schema</i> objects) were introduced with R12 (Matlab 6.0). UDD has been a foundation platform for a number of core Matlab technologies. MathWorks have consistently maintained that UDD is only meant for internal development and not for Matlab users. So, while UDD has no formal documentation, there are plenty of examples and tools to help us learn about it.<br />
It is somewhat odd that despite Matlab&#8217;s new object-oriented system (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_oop/bri1rtu.html">MCOS</a>)&#8217;s introduction 3 years ago, and the <a target="_blank" href="/articles/tag/hg2/">ongoing concurrent development of HG2</a> classes, the older-technology UDD is still being actively developed, as evidenced by the increasing number of UDD classes in recent releases. More background on the differences between these different sets of classes can be found <a target="_blank" href="/articles/new-information-on-hg2/">here</a>.</p>
<h3 id="WhyBother">Why should we bother learning UDD?</h3>
<p>There are some things to consider before deciding if you want to spend the time to learn about the UDD class system:</p>
<h4 id="Pros">The case against studying UDD classes</h4>
<ul>
<li>There is no documentation from The MathWorks for these classes</li>
<li>You will not get any help from The MathWorks in applying these classes</li>
<li>The UDD system is now more than a decade old and may be phased out in future Matlab releases (perhaps in HG2?)</li>
</ul>
<h4 id="Cons">The case for studying UDD classes</h4>
<ul>
<li>UDD is currently the foundation of handle graphics, Java integration, COM, and Simulink</li>
<li>The m code versions of UDD may be considered a forerunner of the newer MCOS class system</li>
<li>To avoid memory leaks when using Callbacks in GUI applications you currently need to use UDD</li>
<li>UDD techniques facilitate Matlab interaction with Java GUIs</li>
<li>UDD directly supports the Matlab style method invocation as well as dot notation for methods without the need to write subsasgn and subsref routines</li>
</ul>
<h3 id="Tools">Tools for Learning about UDD</h3>
<p>We start by describing some undocumented Matlab tools that will help us investigate and understand UDD classes.</p>
<ul>
<li><i><b>findpackage</b></i> &#8211; All UDD Classes are defined as members of a package. findpackage takes the package name as an input argument and returns a schema.package object which provides information about the package</li>
<li><i><b>findclass</b></i> &#8211; This method of the schema.package object returns a schema.class object of the named class if the class exists in the package</li>
<li><i><b>classhandle</b></i> &#8211; For a given UDD object <i><b>classhandle</b></i> returns a schema.class object with information about the class. <i><b>classhandle</b></i> and <i><b>findclass</b></i> are two ways of getting the same information about a UDD class. <i><b>findclass</b></i> works with a <i><b>schema.package</b></i> object and a class name and does not require an instance of the class. <i><b>classhandle</b></i> works with an instance of a class</li>
<li><i><b>findprop</b></i> &#8211; This method of the schema.class object returns a schema.prop object which contains information about the named property</li>
<li><i><b>findevent</b></i> &#8211; This method of the schema.class object returns a schema.prop object which contains information about the named event</li>
<li><i><b>handle</b></i> &#8211; handle is a multifaceted and unique term for The MathWorks. There are both UDD and MCOS handle classes. There is a UDD handle package. In terms of the tools we need, <i><b>handle</b></i> is also an undocumented function which converts a numeric handle into a UDD handle object. Depending on your background you may want to think of <i><b>handle</b></i> as a cast operator which casts a numeric handle into a UDD object.</li>
<li><i><b>methods</b></i> &#8211; This is used to display the methods of an object</li>
<li><i><b>methodsview</b></i> &#8211; Provides a graphic display of an objects methods</li>
<li><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object"><i><b>uiinspect</b></i></a> &#8211; Yair Altman&#8217;s object inspection tool, which can be used for COM, Java and Matlab classes (<i><b>uiinspect</b> will be described in a separate article in the near future</i>).</li>
</ul>
<p>Before we apply these tools we need to discuss the basic structure of UDD classes. Let&#8217;s compare them with the newer, well documented MCOS classes:<br />
MCOS classes can be defined simply as a standalone class or scoped by placing the class in a package or a hierarchy of packages. With UDD, all classes must be defined in a package. UDD Packages are not hierarchical so a UDD package may not contain other packages. UDD classes can always be instantiated with syntax of packageName.className. By default MCOS classes are value classes. With MCOS you can subclass the handle class to create handle classes. UDD classes are handle classes by default, but it is possible to create UDD value classes.</p>
<h3 id="Exploring">Exploring some important built-in UDD Classes</h3>
<p>The current versions of Matlab include a number of built-in UDD packages. We will use our new tools to see what we can learn about these packages. Let us begin by inspecting the two packages that form the basis of the UDD class system.</p>
<h4 id="schema">The schema package</h4>
<p>The built-in schema package contains the classes for creating user written UDD classes. It also is used to provide meta information about UDD classes. Using <i><b>findpackage</b></i> we will obtain a schema.package object for the schema package and then use it obtain information about the classes it contains:</p>
<pre lang="matlab">
>> pkg = findpackage('schema')
pkg =
        schema.package
>> pkg.get
               Name: 'schema'
    DefaultDatabase: [1x1 handle.Database]
            Classes: [9x1 schema.class]
          Functions: [0x1 handle]
        JavaPackage: ''
         Documented: 'on'
</pre>
<p>Note that here we have used the dot-notation pkg.<i><b>get</b></i> &#8211; we could also have used the Matlab notation <i><b>get</b>(pkg)</i> instead.<br />
We have now learned that that there are nine classes in the schema package. The information about them in a schema package&#8217;s <b>Classes</b> property. To see the information about individual classes we inspect this property:</p>
<pre lang="matlab">
>> pkg.Classes(1).get
               Name: 'class'
            Package: [1x1 schema.package]
        Description: ''
        AccessFlags: {0x1 cell}
             Global: 'off'
             Handle: 'on'
       Superclasses: [0x1 handle]
    SuperiorClasses: {0x1 cell}
    InferiorClasses: {0x1 cell}
            Methods: [4x1 schema.method]
         Properties: [13x1 schema.prop]
             Events: []
     JavaInterfaces: {0x1 cell}
</pre>
<p>Not surprisingly, the first class in the schema.package is &#8216;class&#8217; itself. Here we can see that schema.class has 4 methods and 13 properties. We can also see that the schema.class objects have a <b>Name</b> property. Let&#8217;s use that information to list all the classes in the schema package:</p>
<pre lang="matlab">
>> names = cell(numel(pkg.Classes), 1);
>> for index = 1:numel(names), names{index} = pkg.Classes(index).Name; end;
>> names
names =
    'class'
    'method'
    'signature'
    'package'
    'event'
    'prop'
    'type'
    'EnumType'
    'UserType'
</pre>
<p>These are the base classes for the UDD package schema. To illustrate a different way to get information, let&#8217;s use the <i><b>findclass</b></i> method of schema.package to get information about the schema.prop class:</p>
<pre lang="matlab">
>> p = findclass(pkg, 'prop')
p =
        schema.class
>> get(p)
               Name: 'prop'
            Package: [1x1 schema.package]
        Description: ''
        AccessFlags: {0x1 cell}
             Global: 'off'
             Handle: 'on'
       Superclasses: [0x1 handle]
    SuperiorClasses: {0x1 cell}
    InferiorClasses: {0x1 cell}
            Methods: [2x1 schema.method]
         Properties: [9x1 schema.prop]
             Events: []
     JavaInterfaces: {0x1 cell}
</pre>
<h4 id="handle">The handle package</h4>
<p>The second basic UDD package is the handle package. Handle holds a special place in Matlab and has multiple meanings: Handle is a type of Matlab object that is passed by reference; <i><b>handle</b></i> is a function which converts a numeric handle to an object; handle is an abstract object in the new MCOS class system and handle is also a UDD package as well as the default type for UDD objects.<br />
There is an interesting connection between UDD and MCOS that involves handle. In Matlab releases R12 through R2007b, the UDD handle package had up to 12 classes and did not have any package functions (package functions are functions which are scoped to a package; their calling syntax is [outputs] = packageName.<i>functionName(inputs)</i>).<br />
Beginning with the formal introduction of MCOS in R2008a, the abstract MCOS class handle was introduced. The MCOS handle class has 12 methods. It also turns out that beginning with R2008a, the UDD handle package has 12 package functions which are the MCOS handle methods.<br />
The 12 UDD classes in the handle package fall into two groups: The database and transaction classes work with the schema.package to provide a UDD stack mechanism; the listener and family of EventData classes work with schema.event to provide the UDD event mechanism:</p>
<pre lang="matlab">
>> pkg = findpackage('handle')
pkg =
        schema.package
>> pkg.get
               Name: 'handle'
    DefaultDatabase: [1x1 handle.Database]
            Classes: [12x1 schema.class]
          Functions: [12x1 schema.method]
        JavaPackage: ''
         Documented: 'on'
>> names = cell(numel(pkg.Classes), 1);
>> for index = 1:numel(names), names{index} = pkg.Classes(index).Name; end
>> names
names =
    'Operation'
    'transaction'
    'Database'
    'EventData'
    'ClassEventData'
    'ChildEventData'
    'ParentEventData'
    'PropertyEventData'
    'PropertySetEventData'
    'listener'
    'JavaEventData'
    'subreference__'
</pre>
<h4 id="hg">The hg package</h4>
<p>Arguably the most important UDD package in Matlab is the handle graphics package hg. Among the built-in UDD packages, hg is unique in several respects. As Matlab has evolved from R12 through R2011a, the number of default classes in the hg package has nearly doubled going from 17 classes to 30 (UDD has a mechanism for automatically defining additional classes as needed during run-time).<br />
The hg package contains a mixture of Global and non Global classes. These classes return a numeric handle, unless they have been created using package scope. The uitools m-file package provides a great example of extending built-in UDD classes with user written m-file UDD classes.<br />
The UDD class for a Handle-Graphics object can be obtained either by explicitly creating it with the hg package, or using the <i><b>handle</b></i> function on the numeric handle obtained from normal hg object creation. Using figure as an example, you can either use figh = hg.figure or fig = <i><b>figure</b></i> followed by figh = <i><b>handle</b></i>(fig):</p>
<pre lang="matlab">
>> pkg = findpackage('hg')
pkg =
        schema.package
>> pkg.get
               Name: 'hg'
    DefaultDatabase: [1x1 handle.Database]
            Classes: [30x1 schema.class]
          Functions: [0x1 handle]
        JavaPackage: 'com.mathworks.hg'
         Documented: 'on'
>> for index = 1:numel(names), names{index} = pkg.Classes(index).Name; end
>> names
names =
    'GObject'
    'root'
    'LegendEntry'
    'Annotation'
    'figure'
    'uimenu'
    'uicontextmenu'
    'uicontrol'
    'uitable'
    'uicontainer'
    'hgjavacomponent'
    'uipanel'
    'uiflowcontainer'
    'uigridcontainer'
    'uitoolbar'
    'uipushtool'
    'uisplittool'
    'uitogglesplittool'
    'uitoggletool'
    'axes'
    'hggroup'
    'text'
    'line'
    'patch'
    'surface'
    'rectangle'
    'light'
    'image'
    'hgtransform'
    'uimcosadapter'
</pre>
<p>So far we have just explored the very basic concepts of UDD. You may well be wondering what the big fuss is about, since the information presented so far does not have any immediately-apparent benefits.<br />
The following set of articles will describe more advanced topics in UDD usage and customizations, using the building blocks presented today. Hopefully you will quickly understand how using UDD can help achieve some very interesting stuff with Matlab.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/introduction-to-udd">Introduction to UDD</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-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>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
<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/new-information-on-hg2" rel="bookmark" title="New information on HG2">New information on HG2 </a> <small>More information on Matlab's new HG2 object-oriented handle-graphics system...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/introduction-to-udd/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
