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

<channel>
	<title>schema &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/schema/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 06 Mar 2013 18:00:19 +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>Handle Graphics Behavior</title>
		<link>https://undocumentedmatlab.com/articles/handle-graphics-behavior?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=handle-graphics-behavior</link>
					<comments>https://undocumentedmatlab.com/articles/handle-graphics-behavior#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 06 Mar 2013 18:00:19 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3665</guid>

					<description><![CDATA[<p>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handle-graphics-behavior">Handle Graphics Behavior</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/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</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/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/copyobj-behavior-change-in-hg2" rel="bookmark" title="copyobj behavior change in HG2">copyobj behavior change in HG2 </a> <small>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab&#8217;s Handle Graphics (HG) have been around for ages. Still, to this day it contains many hidden gems. Today I discuss HG&#8217;s <b>Behavior</b> property, which is a standard <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties/">undocumented hidden property</a> of all HG objects.<br />
<b>Behavior</b> is not normally updated directly (although there is absolutely nothing to prevent this), but rather via the <a target="_blank" href="/articles/legend-semi-documented-feature/#Semi-documented">semi-documented</a> built-in accessor functions <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i>. This manner of accessing <b>Behavior</b> is similar to its undocumented sibling property <b>ApplicationData</b>, which is accessed by the corresponding <i><b>getappdata</b></i> and <i><b>setappdata</b></i> functions.</p>
<h3 id="usage">Using HB behaviors</h3>
<p><i><b>hggetbehavior</b></i> with no input args displays a list of all pre-installed HG behaviors:</p>
<pre lang='matlab'>
>> hggetbehavior
   Behavior Object Name         Target Handle
   --------------------------------------------
   'Plotedit'...................Any Graphics Object
   'Print'......................Any Graphics Object
   'Zoom'.......................Axes
   'Pan'........................Axes
   'Rotate3d'...................Axes
   'DataCursor'.................Axes and Axes Children
   'MCodeGeneration'............Axes and Axes Children
   'DataDescriptor'.............Axes and Axes Children
   'PlotTools'..................Any graphics object
   'Linked'.....................Any graphics object
   'Brush'......................Any graphics object
</pre>
<p><span id="more-3665"></span><br />
<i><b>hggetbehavior</b></i> can be passed a specific behavior name (or cell array of names), in which case it returns the relevant behavior object handle(s):</p>
<pre lang='matlab'>
>> hBehavior = hggetbehavior(gca, 'Zoom')
hBehavior =
	graphics.zoombehavior
>> hBehavior = hggetbehavior(gca, {'Zoom', 'Pan'})
hBehavior =
	handle: 1-by-2
</pre>
<p>As the name indicates, the behavior object handle controls the behavior of the relevant action. For example, the behavior object for Zoom contains the following properties:</p>
<pre lang='matlab'>
>> hBehavior = hggetbehavior(gca, 'Zoom');
>> get(hBehavior)
       Enable: 1        % settable: true/false
    Serialize: 1        % settable: true/false
         Name: 'Zoom'   % read-only
        Style: 'both'   % settable: 'horizontal', 'vertical' or 'both'
</pre>
<p>By setting the behavior&#8217;s properties, we can control whether the axes will have horizontal, vertical, 2D or no zooming enabled, regardless of whether or not the toolbar/menu-bar zoom item is selected:</p>
<pre lang='matlab'>
hBehavior.Enable = false;         % or: set(hBehavior,'Enable',false)
hBehavior.Style  = 'horizontal';  % or: set(hBehavior,'Style','horizontal')
</pre>
<p>This mechanism is used internally by Matlab to disable zoom/pan/rotate3d (see <i>%matlabroot%/toolbox/matlab/graphics/@graphics/@zoom/setAllowAxesZoom.m</i> and similarly <i>setAllowAxesPan, setAllowAxesRotate</i>).<br />
At this point, some readers may jump saying that we can already do this via the zoom object handle that is returned by the <i><b>zoom</b></i> function (where the <b>Style</b> property was renamed <b>Motion</b>, but never mind). However, I am just trying to show the general usage. Not all behaviors have similar documented customizable mechanisms. In fact, using behaviors we can control specific behaviors for separate HG handles in the same figure/axes.<br />
For example, we can set a different callback function to different HG handles for displaying a plot data-tip (a.k.a. data cursor). I have explained in the past how to <a target="_blank" href="/articles/controlling-plot-data-tips/">programmatically control data-tips</a>, but doing so relies on the figure <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/datacursormode.html"><i><b>datacursormode</b></i></a>, which is figure-wide. If we want to display different data-tips for different plot handles, we would need to add logic into our custom update function that would change the returned string based on the clicked handle. Using HG behavior we can achieve the same goal much easier:</p>
<pre lang='matlab'>
% Use dataCursorLineFcn() for the line data-tip
bh = hggetbehavior(hLine,'DataCursor');
set(bh,'UpdateFcn',@dataCursorLineFcn);
% Use dataCursorAnnotationFcn() for the annotation data-tip
bh = hggetbehavior(hAnnotation,'DataCursor');
set(bh,'UpdateFcn',{@dataCursorAnnotationFcn,extraData});
</pre>
<p>Note: there is also the related semi-documented function <i><b>hgbehaviorfactory</b></i>, which is used internally by <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i>. I do not see any need for using <i><b>hgbehaviorfactory</b></i> directly, only <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i>.</p>
<h3 id="custom">Custom behaviors</h3>
<p>The standard behavior objects are UDD schema objects (i.e., the old object-oriented mechanism in MATLAB). They are generally located in a separate folder beneath <i>%matlabroot%/toolbox/matlab/graphics/@graphics/</i>. For example, the Zoom behavior object is located in <i>%matlabroot%/toolbox/matlab/graphics/@graphics/@zoombehavior/</i>. These behavior object folders generally contain a <i>schema.m</i> file (that defines the behavior object class and its properties), and a <i>dosupport.m</i> function that returns a logical flag indicating whether or not the behavior is supported for the specified handle. These are pretty standard functions, here is an example:</p>
<pre lang='matlab'>
% Zoom behavior's schema.m:
function schema
% Copyright 2003-2006 The MathWorks, Inc.
pk = findpackage('graphics');
cls = schema.class(pk,'zoombehavior');
p = schema.prop(cls,'Enable','bool');
p.FactoryValue = true;
p = schema.prop(cls,'Serialize','MATLAB array');
p.FactoryValue = true;
p.AccessFlags.Serialize = 'off';
p = schema.prop(cls,'Name','string');
p.AccessFlags.PublicSet = 'off';
p.AccessFlags.PublicGet = 'on';
p.FactoryValue = 'Zoom';
p.AccessFlags.Serialize = 'off';
% Enumeration Style Type
if (isempty(findtype('StyleChoice')))
    schema.EnumType('StyleChoice',{'horizontal','vertical','both'});
end
p = schema.prop(cls,'Style','StyleChoice');
p.FactoryValue = 'both';
</pre>
<pre lang='matlab'>
% Zoom behavior's dosupport.m:
function [ret] = dosupport(~,hTarget)
% Copyright 2003-2009 The MathWorks, Inc.
% axes
ret = ishghandle(hTarget,'axes');
</pre>
<p>All behaviors must define the <b>Name</b> property, and most behaviors also define the <b>Serialize</b> and <b>Enable</b> properties. In addition, different behaviors define other properties. For example, the DataCursor behavior defines the <b>CreateNewDatatip</b> flag and no less than 7 callbacks:</p>
<pre lang='matlab'>
function schema
% Copyright 2003-2008 The MathWorks, Inc.
pk = findpackage('graphics');
cls = schema.class(pk,'datacursorbehavior');
p = schema.prop(cls,'Name','string');
p.AccessFlags.PublicSet = 'off';
p.AccessFlags.PublicGet = 'on';
p.FactoryValue = 'DataCursor';
schema.prop(cls,'StartDragFcn','MATLAB callback');
schema.prop(cls,'EndDragFcn','MATLAB callback');
schema.prop(cls,'UpdateFcn','MATLAB callback');
schema.prop(cls,'CreateFcn','MATLAB callback');
schema.prop(cls,'StartCreateFcn','MATLAB callback');
schema.prop(cls,'UpdateDataCursorFcn','MATLAB callback');
schema.prop(cls,'MoveDataCursorFcn','MATLAB callback');
p = schema.prop(cls,'CreateNewDatatip','bool');
p.FactoryValue = false;
p.Description = 'True will create a new datatip for every mouse click';
p = schema.prop(cls,'Enable','bool');
p.FactoryValue = true;
p = schema.prop(cls,'Serialize','MATLAB array');
p.FactoryValue = true;
p.AccessFlags.Serialize = 'off';
</pre>
<p>Why am I telling you all this? Because in addition to the standard behavior objects we can also specify custom behaviors to HG handles. All we need to do is mimic one of the standard behavior object classes in a user-defined class, and then use <i><b>hgaddbehavior</b></i> to add the behavior to an HG handle. Behaviors are differentiated by their <b>Name</b> property, so we can either use a new name for the new behavior, or override a standard behavior by reusing its name.</p>
<pre lang='matlab'>hgaddbehavior(hLine,myNewBehaviorObject)</pre>
<p>If you wish the behavior to be serialized (saved) to disk when saving the figure, you should add the <b>Serialize</b> property to the class and set it to <code>true</code>, then use <i><b>hgaddbehavior</b></i> to add the behavior to the relevant HG handle. The <b>Serialize</b> property is searched-for by the <i><b>hgsaveStructDbl</b></i> function when saving figures (I described <i><b>hgsaveStructDbl</b></i> <a target="_blank" href="/articles/handle2struct-struct2handle-and-matlab-8/">here</a>). All the standard behaviors except DataDescriptor have the <b>Serialize</b> property (I don&#8217;t know why DataDescriptor doesn&#8217;t).<br />
Just for the record, you can also use MCOS (not just UDD) class objects for the custom behavior, as mentioned by the internal comment within the <i><b>hgbehaviorfactory</b></i> function. Most standard behaviors use UDD schema classes; an example of an MCOS behavior is PlotEdit that is found at <i>%matlabroot%/toolbox/matlab/graphics/+graphics/+internal/@PlotEditBehavor/PlotEditBehavor.m</i>.</p>
<h3 id="ishghandle"><i>ishghandle</i>&#8216;s undocumented type input arg</h3>
<p>Note that the Zoom behavior&#8217;s <i>dosupport</i> function uses an undocumented format of the built-in <i><b>ishghandle</b></i> function, namely accepting a second parameter that specifies a specific handle type, which presumably needs to correspond to the handle&#8217;s <b>Type</b> property:</p>
<pre lang='matlab'>ret = ishghandle(hTarget,'axes');</pre>
<h3 id="hasbehavior">The <i>hasbehavior</i> function</h3>
<p>Another semi-documented built-in function called <i><b>hasbehavior</b></i> is located right next to <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i> in the <i>%matlabroot%/toolbox/matlab/graphics/</i> folder.<br />
Despite its name, and the internal comments that specifically mention HG behaviors, this function is entirely independent of the HG behavior mechanism described above, and in fact makes use of the <b>ApplicationData</b> property rather than <b>Behavior</b>. I have no idea why this is so. It may be a design oversight or some half-baked attempt by a Mathworker apprentice to emulate the behavior mechanism. Even the function name is misleading: in fact, <i><b>hasbehavior</b></i> not only checks whether a handle has some &#8220;behavior&#8221; (in the 2-input args format) but also sets this flag (in the 3-input args format).<br />
<i><b>hasbehavior</b></i> is used internally by the legend mechanism, to determine whether or not an HG object (line, scatter group, patch, annotation etc.) should be added to the legend. This can be very important for <a target="_blank" href="/articles/plot-performance/#Legend">plot performance</a>, since the legend would not need to be updated whenever these objects are modified in some manner:</p>
<pre lang='matlab'>
hLines = plot(rand(3,3));
hasbehavior(hLines(1), 'legend', false);   % line will not be in legend
hasbehavior(hLines(2), 'legend', true);    % line will be in legend
</pre>
<p>(for anyone interested, the relevant code that checks this flag is located in <i>%matlabroot%/toolbox/matlab/scribe/private/islegendable.m</i>)<br />
<i><b>hasbehavior</b></i> works by using a dedicated field in the handle&#8217;s <b>ApplicationData</b> struct with a logical flag value (<code>true/false</code>). The relevant field is called <code>[name,'_hgbehavior']</code>, where <code>name</code> is the name of the so-called &#8220;behavior&#8221;. In the example above, it creates a field called &#8220;legend_hgbehavior&#8221;.<br />
Do you know of any neat uses for HG behaviors? If so, please post a comment <a href="/articles/handle-graphics-behavior/#respond">below</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handle-graphics-behavior">Handle Graphics Behavior</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/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</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/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/copyobj-behavior-change-in-hg2" rel="bookmark" title="copyobj behavior change in HG2">copyobj behavior change in HG2 </a> <small>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/handle-graphics-behavior/feed</wfw:commentRss>
			<slash:comments>6</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>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 fetchpriority="high" 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>
