<?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>Undocumented Matlab &#187; Guest bloggers</title> <atom:link href="http://undocumentedmatlab.com/blog/category/guest-bloggers/feed/" rel="self" type="application/rss+xml" /><link>http://undocumentedmatlab.com</link> <description>Charting Matlab's unsupported hidden underbelly</description> <lastBuildDate>Thu, 17 May 2012 12:01:26 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.1.1</generator> <item><title>Extending a Java class with UDD</title><link>http://undocumentedmatlab.com/blog/extending-a-java-class-with-udd/</link> <comments>http://undocumentedmatlab.com/blog/extending-a-java-class-with-udd/#comments</comments> <pubDate>Thu, 29 Mar 2012 14:32:46 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[Java classes can easily be extended in Matlab, using pure Matlab code.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/fixing-a-java-focus-problem/' rel='bookmark' title='Fixing a Java focus problem'>Fixing a Java focus problem</a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li></ol><pre> </pre>]]></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="http://undocumentedmatlab.com/?s=UDD">series on UDD</a>, we have mentioned the connection between UDD and Java. In <a
target="_blank" href="http://undocumentedmatlab.com/blog/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="http://undocumentedmatlab.com/blog/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.</p><p>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).</p><p>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="http://UndocumentedMatlab.com/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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%SCHEMA  simple package definition function.</span>
   schema.<span style="">package</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema.<span style="">m</span>
<span style="color: #228B22;">%SCHEMA  simple.ServerSocket class definition function.</span>
&nbsp;
    <span style="color: #228B22;">% parent schema.class definition</span>
    javaPackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javahandle'</span><span style="color: #080;">&#41;</span>;
    javaClass = findclass<span style="color: #080;">&#40;</span>javaPackage, <span style="color:#A020F0;">'java.net.ServerSocket'</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% class package (schema.package)</span>
    simplePackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% class definition</span>
    simpleClass = schema.<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>simplePackage, <span style="color:#A020F0;">'ServerSocket'</span>, javaClass<span style="color: #080;">&#41;</span>;</pre></div></div><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>.</p><p>Next, in the class definition file we place the code to define the signatures for the methods we are overloading:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">    <span style="color: #228B22;">% accept.m overloads java accept method and adds communication protocol</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'accept'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'string'</span><span style="color: #080;">&#125;</span>;
&nbsp;
    <span style="color: #228B22;">% bind.m overloads java bind method</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'bind'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>;be</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">    <span style="color: #228B22;">% holds remote address as a matlab string</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'address'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color:#A020F0;">'localhost'</span>;
&nbsp;
    <span style="color: #228B22;">% holds remote port as a matlab int</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'port'</span>, <span style="color:#A020F0;">'int16'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color: #33f;">2222</span>;
&nbsp;
    <span style="color: #228B22;">% holds a handle reference to the socket created in the accept method</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'socket'</span>, <span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> bind<span style="color: #080;">&#40;</span>this<span style="color: #080;">&#41;</span>
    <span style="color: #228B22;">% use the object socket and port port properties to bind this instance</span>
    <span style="color: #228B22;">% to a address calling the superclass bind method</span>
    inetAddress = java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#40;</span>this.<span style="">address</span>, this.<span style="">port</span><span style="color: #080;">&#41;</span>;
    this.<span style="">java</span>.<span style="">bind</span><span style="color: #080;">&#40;</span>inetAddress<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> accept<span style="color: #080;">&#40;</span>this<span style="color: #080;">&#41;</span>
&nbsp;
    <span style="color: #228B22;">% use the superclass accept</span>
    this.<span style="">socket</span> = handle<span style="color: #080;">&#40;</span>this.<span style="">java</span>.<span style="">accept</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% infinate loop use ctrl-c to exit</span>
    <span style="color: #0000FF;">while</span> <span style="color: #33f;">1</span>
        <span style="color: #228B22;">% wait for a command then execute it capturing output</span>
        <span style="color: #0000FF;">while</span> this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">available</span> &lt; <span style="color: #33f;">2</span>
        <span style="color: #0000FF;">end</span>
&nbsp;
        msb = this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">read</span>;
        lsb = this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">read</span>;
&nbsp;
        numChar = <span style="color: #33f;">256</span> * msb + lsb;
        cmd = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>, numChar<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">for</span> index = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span>numChar
            cmd<span style="color: #080;">&#40;</span>index<span style="color: #080;">&#41;</span> = this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">read</span>;
        <span style="color: #0000FF;">end</span>
        result = <span style="color: #0000FF;">evalc</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>cmd<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
        <span style="color: #228B22;">% send the result back to the calling system</span>
        len = numel<span style="color: #080;">&#40;</span>result<span style="color: #080;">&#41;</span>;
        msb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">floor</span><span style="color: #080;">&#40;</span>len/<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
        lsb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">mod</span><span style="color: #080;">&#40;</span>len,<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
        this.<span style="">socket</span>.<span style="">getOutputStream</span>.<span style="">write</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>msb, lsb, result<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><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&#8217;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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema
<span style="color: #228B22;">%SCHEMA  simple.Socket class definition function.</span>
&nbsp;
    <span style="color: #228B22;">% package definition</span>
    simplePackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
    javaPackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javahandle'</span><span style="color: #080;">&#41;</span>;
    javaClass = findclass<span style="color: #080;">&#40;</span>javaPackage, <span style="color:#A020F0;">'java.net.Socket'</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% class definition</span>
    simpleClass = schema.<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>simplePackage, <span style="color:#A020F0;">'Socket'</span>, javaClass<span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% define class methods</span>
    <span style="color: #228B22;">% connect.m overloads java connect method</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'connect'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>;
&nbsp;
    <span style="color: #228B22;">% remoteEval.m matlab method for remote evaluation of Matlab commands</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'remoteEval'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'string'</span><span style="color: #080;">&#125;</span>;
&nbsp;
    <span style="color: #228B22;">% add properties to this class</span>
    <span style="color: #228B22;">% holds remote address as a Matlab string</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'address'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color:#A020F0;">'localhost'</span>;
&nbsp;
    <span style="color: #228B22;">% holds remote port as a Matlab int</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'port'</span>, <span style="color:#A020F0;">'int16'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color: #33f;">2222</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>The class constructor <i>Socket.m</i> is simply:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> skt = Socket
<span style="color: #228B22;">%SOCKET constructor for the simple.Socket class</span>
    skt = simple.<span style="">Socket</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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's <i>connect</i> Java method:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> connect<span style="color: #080;">&#40;</span>this<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%CONNECT overload of the java.net.Socket connect method</span>
    <span style="color: #228B22;">% use the object address and port properties to connect to the remote</span>
    <span style="color: #228B22;">% session via the superclass connect method</span>
    inetAddress = java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#40;</span>this.<span style="">address</span>, this.<span style="">port</span><span style="color: #080;">&#41;</span>;
    this.<span style="">java</span>.<span style="">connect</span><span style="color: #080;">&#40;</span>inetAddress<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> result = remoteEval<span style="color: #080;">&#40;</span>this, cmd<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%REMOTEEVAL evaluate a Matlab command on a remotely connected Matlab</span>
&nbsp;
    <span style="color: #228B22;">% The command string is sent as a series of bytes preceded by a pair of</span>
    <span style="color: #228B22;">% bytes which represents the length of the string  </span>
    cmd = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span>cmd<span style="color: #080;">&#41;</span>;
&nbsp;
    len = numel<span style="color: #080;">&#40;</span>cmd<span style="color: #080;">&#41;</span>;
    msb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">floor</span><span style="color: #080;">&#40;</span>len/<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    lsb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">mod</span><span style="color: #080;">&#40;</span>len,<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
    this.<span style="">getOutputStream</span>.<span style="">write</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>msb, lsb, cmd<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% We will expect the remote session to return a string in the same format</span>
    <span style="color: #228B22;">% as the command</span>
    <span style="color: #0000FF;">while</span> this.<span style="">getInputStream</span>.<span style="">available</span> &lt; <span style="color: #33f;">2</span>
    <span style="color: #0000FF;">end</span>
&nbsp;
    msb = this.<span style="">getInputStream</span>.<span style="">read</span>;
    lsb = this.<span style="">getInputStream</span>.<span style="">read</span>;
&nbsp;
    numChar = <span style="color: #33f;">256</span> * msb + lsb;
&nbsp;
    result = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>, numChar<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">for</span> index = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span>numChar
        result<span style="color: #080;">&#40;</span>index<span style="color: #080;">&#41;</span> = this.<span style="">getInputStream</span>.<span style="">read</span>;
    <span style="color: #0000FF;">end</span>
    result = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>result<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; ss = simple.<span style="">ServerSocket</span>;
&gt;&gt; ss.<span style="">bind</span>;
&gt;&gt; ss.<span style="">accept</span>;</pre></div></div><p>Then open another Matlab instance and issue these commands:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; s = simple.<span style="">Socket</span>;
&gt;&gt; s.<span style="">connect</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; remoteResult = s.<span style="">remoteEval</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'pi'</span><span style="color: #080;">&#41;</span>
remoteResult =
    <span style="color: #33f;">3.1416</span></pre></div></div><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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; s.<span style="color: #0000FF;">methods</span>
&nbsp;
<span style="color: #0000FF;">Methods</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">class</span> simple.<span style="">Socket</span><span style="color: #F0F;">:</span>
&nbsp;
Socket                     getOOBInline               isClosed                   setReuseAddress            
bind                       getOutputStream            isConnected                setSendBufferSize          
<span style="color: #0000FF;">close</span>                      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></div></div><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="http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/#struct">previously discussed</a>, we obtain:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt;  <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>s<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = 
              OOBInline<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
                  Bound<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
                Channel<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
                  <span style="color: #0000FF;">Class</span><span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span><span style="color: #080;">&#93;</span>
                 Closed<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
              Connected<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
            InetAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">Inet4Address</span><span style="color: #080;">&#93;</span>
          InputShutdown<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
            InputStream<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">SocketInputStream</span><span style="color: #080;">&#93;</span>
              KeepAlive<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
           LocalAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">Inet4Address</span><span style="color: #080;">&#93;</span>
              LocalPort<span style="color: #F0F;">:</span> <span style="color: #33f;">51269</span>
     LocalSocketAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#93;</span>
         OutputShutdown<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
           OutputStream<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">SocketOutputStream</span><span style="color: #080;">&#93;</span>
      ReceiveBufferSize<span style="color: #F0F;">:</span> <span style="color: #33f;">8192</span>
    RemoteSocketAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#93;</span>
           ReuseAddress<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
         SendBufferSize<span style="color: #F0F;">:</span> <span style="color: #33f;">8192</span>
               SoLinger<span style="color: #F0F;">:</span> -<span style="color: #33f;">1</span>
              SoTimeout<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
             TcpNoDelay<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
           TrafficClass<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
                address<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'localhost'</span>
                   port<span style="color: #F0F;">:</span> <span style="color: #33f;">2222</span></pre></div></div><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><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/fixing-a-java-focus-problem/' rel='bookmark' title='Fixing a Java focus problem'>Fixing a Java focus problem</a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/extending-a-java-class-with-udd/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Expanding urlread capabilities</title><link>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/</link> <comments>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/#comments</comments> <pubDate>Wed, 21 Mar 2012 18:00:01 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Jim Hokanson]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2808</guid> <description><![CDATA[The built-in urlread functions has severe limitations. This article explains how to solve them.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/undocumented-xml-functionality/' rel='bookmark' title='Undocumented XML functionality'>Undocumented XML functionality</a> <small>Matlab's built-in XML-processing functions have several undocumented features that can be used by Java-savvy users...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-robot/' rel='bookmark' title='GUI automation using a Robot'>GUI automation using a Robot</a> <small>This article explains how Java's Robot class can be used to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-utilities/' rel='bookmark' title='GUI automation utilities'>GUI automation utilities</a> <small>This article explains a couple of Matlab utilities that use Java's Robot class to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://sites.google.com/site/jimhokanson/">Jim Hokanson</a>. Today, Jim will explain some of the limitations that at one time or another many of us have encountered with Matlab&#8217;s built-in <b>urlread</b> function. More importantly, Jim has spent a lot of time in creating an expanded-capabilities Matlab function, which he explains below. Note that while <b>urlread</b>&#8216;s internals are undocumented, the changes outlined below rely on pretty standard Java and HTTP, and should therefore be quite safe to use on multiple Matlab versions.</i></p><h3 id="Abstract">Abstract</h3><p>I recently tried to implement the <a
target="_blank" rel="nofollow" href="http://dev.mendeley.com">Mendeley</a> API but quickly found that <i><b>urlread</b></i> was not going to be sufficient for my needs. The first indication of this was my inability to send the proper authorization information for POST requests. It became even more obvious with the need to perform DELETE and PUT methods, since <i><b>urlread</b></i> only supports GET and POST. My implementation of <i><b>urlread</b></i>, which I refer to as <i><b>urlread2</b></i>, addresses these and a couple of other issues and can be <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/35693-urlread2">found on the Matlab File Exchange</a>. Other developers have tackled <i><b>urlread</b></i>&#8216;s shortcomings (<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/8474-rewrites-of-urlread-and-urlwrite">this example</a> added timeout support, and <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/27189-urlreadpost-url-post-method-with-binary-file-uploading">this example</a> added support for binary file upload) &#8211; today&#8217;s article will focus on my solution, but others are obviously possible.</p><h3 id="Introduction">Introduction</h3><p><a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">HTTP</a> is the underlying computer networking protocol that enables us to read webpages on the Internet. It consists of a request made by the user to an Internet server (typically located via <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Uniform_resource_locator">URL</a>), and a response from that server. Importantly, the request and response consist of three main parts: a resource line (for requests) or status line (for responses), followed by headers, and optionally a message body.</p><p>Matlab&#8217;s built-in <i><b>urlread</b></i> function enables Matlab users to easily read the server&#8217;s response text into a Matlab string:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">text = urlread<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'http://www.google.com'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This is done internally using Java code that connects to the specified URL and reads the information sent by the URL&#8217;s server (<a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/networking/urls/index.html">more on this</a>).</p><p><i><b>urlread</b></i> accepts optional additional inputs specifying the request type (&#8216;get&#8217; or &#8216;post&#8217;) and parameter values for the request.</p><p>Unfortunately, <i><b>urlread</b></i> has the following limitations:</p><ol><li>It does not allow specification of request headers</li><li>It makes assumptions as to the request headers needed based on the input method</li><li>It does not expose the response headers and status line</li><li>It assumes the response body contains text, and not a binary payload</li><li>It does not enable uploading binary contents to the server</li><li>It does not enable specifying a timeout in case the server is not responding</li></ol><h3 id="urlread2">urlread2</h3><p>The <i><b>urlread2</b></i> function addresses all of these problems. The overall design decision for this function was to make it more general, requiring more work up front to use in some cases, but more flexibility.</p><p>For reference, the following is the calling format for <i><b>urlread2</b></i> (which is reminiscent of <i><b>urlread</b></i>&#8216;s):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">urlread2<span style="color: #080;">&#40;</span>url,*method,*body,*headersIn, <span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span></pre></div></div><p>The * indicate optional inputs that must be spatially maintained.</p><ul><li>url &#8211; (string), url to request</li><li>method &#8211; (string, default GET) HTTP request method</li><li>body &#8211; (string, default &#8221;), body of the request</li><li>headersIn &#8211; (structure, default []), see the following section</li><li>varargin &#8211; extra properties that need to be specified via property/pair values</li></ul><h3 id="Headers">Addressing Problem 1 &#8211; Request header</h3><p><i><b>urlread</b></i> internally uses a Java object called <code>urlConnection</code> that is generally an instance of the class <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html"><code>sun.net.www.protocol.http.HttpURLConnection</code></a>. The method <i>setRequestProperty()</i> can be used to set headers for the request. This method has two inputs, the header name and the value of that header. A simple example of this can be seen below:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">urlConnection.<span style="">setRequestProperty</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Content-Type'</span>,<span style="color:#A020F0;">'application/x-www-form-urlencoded'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Here &#8216;Content-Type&#8217; is the header name and the second input is the value of that property. My function requires passing in nearly all headers as a structure array, with fields for the name and value. The preceding header would be created using a helper function <i><b>http_createHeader.m</b></i>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">header = http_createHeader<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Content-Type'</span>,<span style="color:#A020F0;">'application/x-www-form-urlencoded'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Multiple headers can be passed in to the function by concatenating header structures into a structure array.</p><h3 id="Parameters">Addressing Problem 2 &#8211; Request parameters</h3><p>When making a POST request, parameters are generally specified in the message body using the following format:</p><p><code>[property]=[value]&#038;[property]=[value]</code></p><p>The properties and values are also encoded in a particular way, generally termed <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Percent-encoding">urlencoded</a> (encoding and decoding can be done using Matlab&#8217;s built-in <i><b>urlencode</b></i> and <i><b>urldecode</b></i> functions). For GET requests this string is appended to the url with the &#8220;?&#8221; symbol. Since urlencoding methods can vary, and in the spirit of reducing assumptions, I use separate functions to generate these strings outside of <i><b>urlread2</b></i>, and then pass the result in either as the url (for GET) or as the body input (for POST). As an example, I might <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/?search_submit=fileexchange&#038;term=undocumented+matlab&#038;query=undocumented+matlab">search the Mathworks website</a> using the upper right search bar on its site for &#8220;undocumented matlab&#8221; under file exchange (<i>hmmm&#8230; pretty cute stuff there!</i>). Doing this performs a GET request with the following property/value pairs:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">params = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'search_submit'</span>,<span style="color:#A020F0;">'fileexchange'</span>, <span style="color:#A020F0;">'term'</span>,<span style="color:#A020F0;">'undocumented matlab'</span>, <span style="color:#A020F0;">'query'</span>,<span style="color:#A020F0;">'undocumented matlab'</span><span style="color: #080;">&#125;</span>;</pre></div></div><p>These property/value pairs are somewhat obvious from looking at the URL, but could also be determined by using programs such as <a
target="_blank" rel="nofollow" href="http://www.fiddler2.com/fiddler2/">Fiddler</a>, <a
target="_blank" rel="nofollow" href="http://getfirebug.com/">Firebug</a>, or <a
target="_blank" rel="nofollow" href="http://www.httpwatch.com/">HttpWatch</a>.</p><p>After urlencoding and concatenating, we would form the following string:</p><p><code>search_submit=fileexchange&#038;term=undocumented+matlab&#038;query=undocumented+matlab</code></p><p>This functionality is normally accomplished internally in <i><b>urlread</b></i>, but I use a function <i><b>http_paramsToString</b></i> to produce that result. That function also returns the required header for POST requests. The following is an example of both GET and POST requests:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #080;">&#91;</span>queryString,header<span style="color: #080;">&#93;</span> = http_paramsToString<span style="color: #080;">&#40;</span>params,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% For GET:</span>
url = <span style="color: #080;">&#91;</span>url <span style="color:#A020F0;">'?'</span> queryString<span style="color: #080;">&#93;</span>;
urlread2<span style="color: #080;">&#40;</span>url<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">% For POST:</span>
urlread2<span style="color: #080;">&#40;</span>url,<span style="color:#A020F0;">'POST'</span>,queryString,header<span style="color: #080;">&#41;</span></pre></div></div><h3 id="Response">Addressing Problem 3 &#8211; Response header</h3><p>According to the HTTP protocol, each server response starts with a simple header that indicates a numeric <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes">response status</a>. The following Matlab code provides access to the status line using the <code>urlConnection</code> object:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">status = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'value'</span>,urlConnection.<span style="">getResponseCode</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'msg'</span>,<span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getResponseMessage</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
status = 
    value<span style="color: #F0F;">:</span> <span style="color: #33f;">200</span>
      msg<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'OK'</span></pre></div></div><p><code>urlConnection</code>&#8216;s <i>getHeaderField()</i> and <i>getHeaderFieldKey()</i> methods enable reading the specific parts of the response header:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">headerValue = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getHeaderField</span><span style="color: #080;">&#40;</span>headerIndex<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
headerName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getHeaderFieldKey</span><span style="color: #080;">&#40;</span>headerIndex<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><code>headerIndex</code> starts at 0 and increases by 1 until both <code>headerValue</code> and <code>headerName</code> return empty.</p><p>It is important to note that header keys (names) can be repeated for different values. Sometimes this is desired, such as if there are multiple cookies being sent to the user. To generically handle this case, two header structures are returned. In both cases the header names are the field names in the structure, after <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/genvarname.html">replacing hyphens with underscores</a>. In one case, allHeaders, the values are cell arrays of strings containing all values presented with the particular key. The other structure, firstHeaders, contains only the first instance of the header as a string to avoid needing to dereference a cell array.</p><h3 id="Body">Addressing Problem 4 &#8211; Response body</h3><p><i><b>urlread</b></i> assumes text output. This is fine for most webpages, which use HTML and are therefore text-based. However, <i><b>urlread</b></i> fails when trying to download any non-text resource such as an image, a ZIP file, or a PDF document. I have added a flag in <i><b>urlread2</b></i> called CAST_OUTPUT, which defaults to true, i.e. text response, just as <i><b>urlread</b></i> assumes. Using <i><b>varargin</b></i>, this flag can be set to false ({&#8216;CAST_OUTPUT&#8217;,false}) to indicate a binary response.</p><h3 id="Summary">Summary</h3><p><i><b>urlread2</b></i>&#8216;s functionality has been expanded to also address other limitations of <i><b>urlread</b></i>: It enables binary inputs, better character-set handling of the output, redirection following, and read timeouts.</p><p>The modifications described above provide direct access to the key components of the HTTP request and response messages. Its more generic nature lets <i><b>urlread2</b></i> focus on HTTP transmission, and leaves request formation and response interpretation up to the user. I think ultimately this approach is better than providing one-off modifications of the original <i><b>urlread</b></i> function to suit a particular need. <i><b>urlread2</b></i> and supporting files can be <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/35693-urlread2">found</a> on the Matlab File Exchange.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/undocumented-xml-functionality/' rel='bookmark' title='Undocumented XML functionality'>Undocumented XML functionality</a> <small>Matlab's built-in XML-processing functions have several undocumented features that can be used by Java-savvy users...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-robot/' rel='bookmark' title='GUI automation using a Robot'>GUI automation using a Robot</a> <small>This article explains how Java's Robot class can be used to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-utilities/' rel='bookmark' title='GUI automation utilities'>GUI automation utilities</a> <small>This article explains a couple of Matlab utilities that use Java's Robot class to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Matlab&#8217;s internal memory representation</title><link>http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/</link> <comments>http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/#comments</comments> <pubDate>Thu, 15 Mar 2012 18:11:23 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Mex]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Peter Li]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2798</guid> <description><![CDATA[Matlab's internal memory structure is explored and discussed.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/' rel='bookmark' title='Matlab mex in-place editing'>Matlab mex in-place editing</a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/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><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>Once again I&#8217;d like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://absurdlycertain.blogspot.com/">Peter Li</a>. Peter wrote about <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/">Matlab Mex in-place editing</a> last month. Today, Peter pokes around in Matlab&#8217;s internal memory representation to the greater good and glory of Matlab Mex programming.</i></p><p><b><i>Disclaimer: The information in this article is provided for informational purposes only.  Be aware that poking into Matlab&#8217;s internals is not condoned or supported by MathWorks, and is not recommended for any regular usage.  Poking into memory has the potential to crash your computer so save your data!  Moreover, be advised (as the text below will show) that the information is highly prone to change without any advance notice in future Matlab releases, which could lead to very adverse effects on any program that relies on it. On the scale of undocumented Matlab topics, this practically breaks the scale, so be EXTREMELY careful when using this.</i></b></p><p>A few weeks ago I <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/">discussed</a> Matlab&#8217;s copy-on-write mechanism as part of my discussion of editing Matlab arrays in-place.  Today I want to explore some behind-the-scenes details of how the copy-on-write mechanism is implemented.  In the process we will learn a little about Matlab&#8217;s internal array representation.  I will also introduce some simple tools you can use to explore more of Matlab&#8217;s internals.  I will only cover basic information, so there are plenty more details left to be filled in by others who are interested.</p><h3 id="Copy-on-write">Brief review of copy-on-write and mxArray</h3><p>Copy-on-write is Matlab&#8217;s mechanism for avoiding unnecessary duplication of data in memory.  To implement this, Matlab needs to keep track internally of which sets of variables are copies of each other.  As described in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f21585.html">MathWorks&#8217;s article</a>, &#8220;<i>the Matlab language works with a single object type: the Matlab array. All Matlab variables (including scalars, vectors, matrices, strings, cell arrays, structures, and objects) are stored as Matlab arrays. In C/C++, the Matlab array is declared to be of type <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/apiref/mxarray.html"><code>mxArray</code></a></i>&#8220;. This means that <code>mxArray</code> defines how Matlab lays out all the information about an array (its Matlab data type, its size, its data, etc.) in memory.  So understanding Matlab&#8217;s internal array representation basically boils down to understanding <code>mxArray</code>.</p><p>Unfortunately, MathWorks also tells us that &#8220;<i><code>mxArray</code> is a C language <a
target='_blank' rel='nofollow' href='http://en.wikipedia.org/wiki/Opaque_pointer'>opaque type</a></i>&#8220;. This means that MathWorks does not expose the organization of <code>mxArray</code> to users (i.e. Matlab or Mex programmers).  Instead, MathWorks defines <code>mxArray</code> internally, and allows users to interact with it only through an API, a set of functions that know how to handle <code>mxArray</code> in their back end.  So, for example, a Mex programmer does not get the dimensions of an <code>mxArray</code> by directly accessing the relevant field in memory.  Instead, the Mex programmer only has a pointer to the <code>mxArray</code>, and passes this pointer into an API function that knows where in memory to find the requested information and then passes the result back to the programmer.</p><p>This is generally a good thing: the API provides an abstraction layer between the programmer and the memory structures so that if MathWorks needs to change the back end organization (to add a new feature for example), we programmers do not need to modify our code; instead MathWorks just updates the API to reflect the new internal organization.  On the other hand, being able to look into the internal structure of <code>mxArray</code> on occasion can help us understand how Matlab works, and can help us write more efficient code if we are careful as in the example of editing arrays in-place.</p><p>So how do we get a glimpse inside <code>mxArray</code>?  The first step is simply to find the region of memory where the <code>mxArray</code> lives: its beginning and end.  Finding where in memory the <code>mxArray</code> begins is pretty easy: it is given by its pointer value.  Here is a simple Mex function that takes a Matlab array as input and prints its memory address:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* printaddr.cpp */</span>
<span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #993333;">void</span> mexFunction<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> nlhs<span style="color: #339933;">,</span> mxArray <span style="color: #339933;">*</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span> nrhs<span style="color: #339933;">,</span> <span style="color: #993333;">const</span> mxArray <span style="color: #339933;">*</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;One input required.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%p<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>This function is nice as it prints the address in a standard hexadecimal format.  The same information can also be received directly in Matlab (i.e., without needing <i><b>printaddr</b></i>), using the undocumented <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/15485#34519"><i><b>format debug</b></i> command</a> (here&#8217;s <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/15988">another reference</a>):</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">format</span> debug
&nbsp;
&gt;&gt; A = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">10</span>
A =
Structure address = 7fc3b8869ae0
m = <span style="color: #33f;">1</span>
n = <span style="color: #33f;">10</span>
pr = 7fc44922c890
<span style="color: #0000FF;">pi</span> = <span style="color: #33f;">0</span>
     <span style="color: #33f;">1</span>     <span style="color: #33f;">2</span>     <span style="color: #33f;">3</span>     <span style="color: #33f;">4</span>     <span style="color: #33f;">5</span>     <span style="color: #33f;">6</span>     <span style="color: #33f;">7</span>     <span style="color: #33f;">8</span>     <span style="color: #33f;">9</span>    <span style="color: #33f;">10</span>
&nbsp;
&gt;&gt; printaddr<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
7fc3b8869ae0</pre></div></div><p>To play with this further from within Matlab however, it's nice to have the address returned to us as a 64-bit unsigned integer; here's a Mex function that does that:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* getaddr.cpp */</span>
<span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #993333;">void</span> mexFunction<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> nlhs<span style="color: #339933;">,</span> mxArray <span style="color: #339933;">*</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span> nrhs<span style="color: #339933;">,</span> <span style="color: #993333;">const</span> mxArray <span style="color: #339933;">*</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;One input required.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   plhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> mxCreateNumericMatrix<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> mxUINT64_CLASS<span style="color: #339933;">,</span> mxREAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> <span style="color: #339933;">*</span>out <span style="color: #339933;">=</span> static_cast<span style="color: #339933;">&lt;</span>unsigned <span style="color: #993333;">long</span> <span style="color: #339933;">*&gt;</span><span style="color: #009900;">&#40;</span>mxGetData<span style="color: #009900;">&#40;</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   out<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span><span style="color: #009900;">&#41;</span> prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>Here's <i><b>getaddr</b></i> in action:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; getaddr<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = 
           <span style="color: #33f;">139870853618400</span>
&nbsp;
<span style="color: #228B22;">% And using pure Matlab:</span>
&gt;&gt; <span style="color: #0000FF;">hex2dec</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'7f36388b5ae0'</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% output of printaddr or format debug</span>
<span style="color: #0000FF;">ans</span> =
           <span style="color: #33f;">139870853618400</span></pre></div></div><p>So now we know where to find our array in memory.  With this information we can already learn a lot.  To make our exploration a little cleaner though, it would be nice to know where the array ends in memory too, in other words we would like to know the size of the <code>mxArray</code>.</p><h3 id="Structure">Finding the structure of mxArray</h3><p>The first thing to understand is that the amount of memory taken by an <code>mxArray</code> does not have anything to do with the dimensions of the array in Matlab.  So a 1x1 Matlab array and a 100x100 Matlab array have the same size <code>mxArray</code> representation in memory.  As you will know if you have experience programming in Mex, this is simply because the Matlab array's data contents are not stored directly within <code>mxArray</code>.  Instead, <code>mxArray</code> only stores a pointer to another memory location where the actual data reside.  This is fine; the internal information we want to poke into is all still in <code>mxArray</code>, and it is easy to get the pointer to the array's data contents using the API functions <i>mxGetData</i> or <i>mxGetPr</i>.</p><p>So we are still left with trying to figure out the size of <code>mxArray</code>.  There are a couple paths forward.  First I want to talk about a historical tool that used to make a lot of this internal information easily available.  This was a function called <i>headerdump</i>, by Peter Boetcher (described <a
target="_blank" rel="nofollow" href="http://www.mit.edu/~pwb/matlab/">here</a> and <a
target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/c241d8821fb90275">here</a>). <i>headerdump</i> was created for exactly the goal we are currently working towards: to understand Matlab's copy-on-write mechanism.  Unfortunately, as Matlab has evolved, newer versions have incrementally broken this useful tool.  So our goal here is to create a replacement.  Still, we can learn a lot from the earlier work.</p><p>One of the things that helped people figure out Matlab's internals in the past is that in older versions of Matlab <code>mxArray</code> is not a completely opaque type.  Even in recent versions up through at least R2010a, if you look into $MATLAB/extern/include/matrix.h you can find a definition of <code>mxArray_tag</code> that looks something like this:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* R2010a */</span>
<span style="color: #993333;">struct</span> mxArray_tag <span style="color: #009900;">&#123;</span>
   <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>reserved<span style="color: #339933;">;</span>
   <span style="color: #993333;">int</span>    reserved1<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
   <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>reserved2<span style="color: #339933;">;</span>
   size_t  number_of_dims<span style="color: #339933;">;</span>
   <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> reserved3<span style="color: #339933;">;</span>
   <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag0  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag1  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag2  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag3  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag4  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag5  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag6  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag7  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag7a <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag8  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag9  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag10 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag11 <span style="color: #339933;">:</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag12 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag13 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>   flags<span style="color: #339933;">;</span>
   size_t reserved4<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
   <span style="color: #993333;">union</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
           <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>
           <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>pimag_data<span style="color: #339933;">;</span>
           <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>reserved5<span style="color: #339933;">;</span>
           size_t reserved6<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
       <span style="color: #009900;">&#125;</span>   number_array<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>   data<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div><p>This is what you could call murky or obfuscated, but not completely opaque.  The fields mostly have unhelpful names like "reserved", but on the other hand we at least have a sense for what fields there are and their layout.</p><p>A more informative (yet unofficial) definition was <a
target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/b8dbd91953c494fb">provided</a> by James Tursa and Peter Boetcher:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #808080; font-style: italic;">/* Definition of structure mxArray_tag for debugging purposes. Might not be fully correct 
 * for Matlab 2006b or 2007a, but the important things are. Thanks to Peter Boettcher.
 */</span>
<span style="color: #993333;">struct</span> mxArray_tag <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">const</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">;</span>
  mxClassID class_id<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span> vartype<span style="color: #339933;">;</span>
  mxArray    <span style="color: #339933;">*</span>crosslink<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>      number_of_dims<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>      refcount<span style="color: #339933;">;</span>
  <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    scalar_flag <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag1 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag2 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag3 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag4 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag5 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag6 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag7 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    private_data_flag <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag8 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag9 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag10 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag11 <span style="color: #339933;">:</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag12 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag13 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>   flags<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  rowdim<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  coldim<span style="color: #339933;">;</span>
  <span style="color: #993333;">union</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #993333;">double</span>  <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>       <span style="color: #666666; font-style: italic;">// original: void*</span>
      <span style="color: #993333;">double</span>  <span style="color: #339933;">*</span>pimag_data<span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// original: void*</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>irptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>jcptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nelements<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nfields<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>   number_array<span style="color: #339933;">;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      mxArray <span style="color: #339933;">**</span>pdata<span style="color: #339933;">;</span>
      <span style="color: #993333;">char</span>  <span style="color: #339933;">*</span>field_names<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>dummy1<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>dummy2<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   dummy3<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nfields<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>   struct_array<span style="color: #339933;">;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>  <span style="color: #808080; font-style: italic;">/*mxGetInfo*/</span>
      <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>field_names<span style="color: #339933;">;</span>
      <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span> checksum<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>  nelements<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>  reserved<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>  object_array<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>   data<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div><p>For comparison, here is another definition from an earlier version of Matlab.</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* R11 aka Matlab 5.0 (1999) */</span>
<span style="color: #993333;">struct</span> mxArray_tag <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">char</span> name<span style="color: #009900;">&#91;</span>mxMAXNAM<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  class_id<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  vartype<span style="color: #339933;">;</span>
  mxArray <span style="color: #339933;">*</span>crosslink<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  number_of_dims<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  nelements_allocated<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  dataflags<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  rowdim<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  coldim<span style="color: #339933;">;</span>
  <span style="color: #993333;">union</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>pimag_data<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>irptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>jcptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   reserved<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nfields<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>   number_array<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>   data<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div><p>I took this R11 definition from the source code to <i>headerdump</i> (specifically, from <i>mxinternals.h</i>, which also has <code>mxArray_tag</code> definitions for R12 (Matlab 6.0) and R13 (Matlab 6.5)), and you can see that it is much more informative, because many fields have been given useful names thanks to the work of Peter Boetcher and others.  Note also that the definition from this old version of Matlab is quite different from the version from R2010a.</p><p>At this point, if you are running a much earlier version of Matlab like R11 or R13, you can break off from the current article and start playing around with <i>headerdump</i> directly to try to understand Matlab's internals.  For more recent versions of Matlab, we have more work to do.  Getting back to our original goal, if we take the <code>mxArray_tag</code> definition from R2010a and run <i>sizeof</i>, we get an answer for the amount of memory taken up by an <code>mxArray</code> in R2010a: <b>104 bytes</b>.</p><h3 id="Size">Determining the size of mxArray</h3><p>It was nice to derive the size of <code>mxArray</code> from actual MathWorks code, but unfortunately this information is no longer available as of R2011a.  Somewhere between R2010a and R2011a, MathWorks stepped up their efforts to make <code>mxArray</code> completely opaque.  So we should find another way to get the size of <code>mxArray</code> for current and future Matlab versions.</p><p>One ugly trick that works is to create many new arrays quickly and see where their starting points end up in memory:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #0000FF;">num2cell</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">100</span><span style="color: #080;">&#41;</span>';
&gt;&gt; addrs = <span style="color: #0000FF;">sort</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">cellfun</span><span style="color: #080;">&#40;</span>@getaddr, A<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>What we did here is create 100 new arrays, and then get all their memory addresses in sorted order.  Now we can take a look at how far apart these new arrays ended up in memory:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">semilogy</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">diff</span><span style="color: #080;">&#40;</span>addrs<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>The resulting plot will look different each time you run this; it is not really predictable where Matlab will put new arrays into memory.  Here is an example from my system:</p><p><center><div
class="wp-caption aligncenter" style="width: 493px"><img
alt="Plot of memory addresses" src="http://UndocumentedMatlab.com/images/mxArray_memory.png" title="Plot of memory addresses" width="483" height="381" /><p
class="wp-caption-text">Plot of memory addresses</p></div></center></p><p>Your results may look different, and you might have to increase the number of new arrays from 100 to 1000 to get the qualitative result, but the important feature of this plot is that there is a minimum distance between new arrays of about 10<sup>2</sup>.  In fact, if we just go straight for this minimum distance:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">min</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">diff</span><span style="color: #080;">&#40;</span>addrs<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = 
            <span style="color: #33f;">104</span></pre></div></div><p>we find that although <code>mxArray</code> has gone completely opaque from R2010a to R2011a, the full size of <code>mxArray</code> in memory has stayed the same: 104 bytes.</p><h3 id="Dump">Dumping mxArray from memory</h3><p>We now have all the information we need to start looking into Matlab's array representation.  There are many tools available that allow you to browse memory locations or dump memory contents to disk.  For our purposes though, it is nice to be able to do everything from within Matlab.  Therefore I introduce a simple tool that prints memory locations into the Matlab console:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* printmem.cpp */</span>
<span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #993333;">void</span> mexFunction<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> nlhs<span style="color: #339933;">,</span> mxArray <span style="color: #339933;">*</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span> nrhs<span style="color: #339933;">,</span> <span style="color: #993333;">const</span> mxArray <span style="color: #339933;">*</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">||</span> <span style="color: #339933;">!</span>mxIsUint64<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> mxIsEmpty<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;First argument must be a uint64 memory address&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> <span style="color: #339933;">*</span>addr <span style="color: #339933;">=</span> static_cast<span style="color: #339933;">&lt;</span>unsigned <span style="color: #993333;">long</span> <span style="color: #339933;">*&gt;</span><span style="color: #009900;">&#40;</span>mxGetData<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>mem <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> addr<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">2</span> <span style="color: #339933;">||</span> <span style="color: #339933;">!</span>mxIsDouble<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> mxIsEmpty<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Second argument must be a double-type integer byte size.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>      
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> nbytes <span style="color: #339933;">=</span> static_cast<span style="color: #339933;">&lt;</span>unsigned int<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>mxGetScalar<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> nbytes<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%.2x &quot;</span><span style="color: #339933;">,</span> mem<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">16</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>Here is how you use it in Matlab:</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #33f;">0</span>;
&gt;&gt; printmem<span style="color: #080;">&#40;</span>getaddr<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>, <span style="color: #33f;">104</span><span style="color: #080;">&#41;</span>
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 <span style="color: #33f;">70</span> fa <span style="color: #33f;">33</span> df 6f 7f 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00</pre></div></div><p>And there you have it: the inner guts of <code>mxArray</code> laid bare.  I have printed each byte as a two character hexadecimal value, as is standard, so there are 16 bytes printed per row.</p><h3 id="">What does it mean?</h3><p>So now we have 104 bytes of Matlab internals to dig into.  We can start playing with this with a few simple examples:</p><pre>
>> A = 0; B = 1;
>> printmem(getaddr(A), 104)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 <span style="background-color:#e6b8af;">c0 b0 27 df 6f 7f</span> 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00

>> printmem(getaddr(B), 104)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 <span style="background-color:#e6b8af;">70 fa 33 df 6f 7f</span> 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00
</pre><p></p><p>In this and subsequent examples, I will highlight bytes that are different or that are of interest.  What we can see from this example is that although arrays A and B have different content, almost nothing is different between their <code>mxArray</code> representations.  What is different, is the memory address stored in the highlighted bytes.  This confirms our earlier assertion that <code>mxArray</code> does not store the array contents, but only a pointer to the content location.</p><p>Now let us try to figure out some of the other fields:</p><pre>
>> A = 1:3; B = 1:10; C = (1:10)';
>> printmem(getaddr(A), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 00 00 00 00 00
00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 <span style="background-color:#e6b8af;">01</span> 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">03</span> 00 00 00 00 00 00 00 60 80 22 df 6f 7f 00 00

>> printmem(getaddr(B), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 00 00 00 00 00
00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 <span style="background-color:#e6b8af;">01</span> 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">0a</span> 00 00 00 00 00 00 00 80 83 29 df 6f 7f 00 00

>> printmem(getaddr(C), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 00 00 00 00 00
00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 <span style="background-color:#e6b8af;">0a</span> 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">01</span> 00 00 00 00 00 00 00 80 83 29 df 6f 7f 00 00
</pre><p></p><p>(Note that this time I only printed the first four lines of each array as this is where the interesting differences are for this example.)</p><p>In <span
style="background-color:#e6b8af;">red</span> I highlighted the bytes in each array that give its number of rows and columns (note that hexadecimal 0a is 10 in decimal).  In <span
style="background-color:#a4c2f4;">blue</span> I highlighted areas that store the value "02", which could be the location for storing the number of dimensions.  Let us look into this more:</p><pre>
>> A = rand([3 3 3]);
>> printmem(getaddr(A), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#e6b8af;">03</span> 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 <span style="background-color:#e6b8af;">30 4a 3f df 6f 7f</span> 00 00
<span style="background-color:#e6b8af;">09</span> 00 00 00 00 00 00 00 b0 d3 24 df 6f 7f 00 00
</pre><p></p><p>Two interesting results here:  The first highlighted region changed from 02 to 03, so this must be the place where <code>mxArray</code> indicates a 3-dimensional array rather than 2D.  Another important thing also changed though: we can see in the second highlighted region that there is a new memory address stored where we used to find the number of rows.  And in the third highlighted region we now have the number 09 instead of the number of columns.</p><p>Clearly, Matlab has a different way of representing a 2D matrix versus arrays of higher dimension such as 3D.  In the 2D case, <code>mxArray</code> simply holds the nrows and ncols directly, but for a higher dimension case we hold only the number of dimensions (03), the total number of elements (09), and a pointer to another memory location (0x7f6fdf3f4a30) which holds the array of sizes for each dimension.</p><h3 id="COW">The copy-on-write mechanism</h3><p>Finally, we are in a position to understand how Matlab internally implements copy-on-write:</p><pre>
>> A = 1:10;
>> printmem(getaddr(A), 64);
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00
0a 00 00 00 00 00 00 00 90 f3 24 df 6f 7f 00 00

>> B = A;
>> printaddr(B);
0x7f6f4c7b6810

>> printmem(getaddr(A), 64);
<span style="background-color:#e6b8af;">10 68 7b 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">10 68 7b 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00
0a 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">90 f3 24 df 6f 7f</span> 00 00
</pre><p></p><p>What we see is that by setting B = A, we change the internal representation of A itself.  Two new memory address pointers are added to the <code>mxArray</code> for A.  As it turns out, both of these point to the address for array B, which makes sense; this is how Matlab internally keeps track of arrays that are copies of each other.  Note that because byte order is <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Endianness">little-endian</a>, the memory addresses from <i><b>printmem</b></i> are byte-wise, i.e. every two characters, reversed relative to the address from <i><b>printaddr</b></i>.</p><p>We can also look into array B:</p><pre>
>> printmem(getaddr(B), 64);
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00
0a 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">90 f3 24 df 6f 7f</span> 00 00

>> printaddr(A);
<span style="background-color:#e6b8af;">0x7f6f4c7a41f0</span>
</pre><p></p><p>As I have highlighted, there are two interesting points here.  First the red highlights show that array B has pointers back to array A.  Second the blue highlight shows that the Matlab data for array B actually just points back to the same memory as the data for array A (the values 1:10).</p><p>Finally, we would like to understand why there are two pointers added.  Let us see what happens if we add a third linked variable:</p><pre>
>> C = B;
>> printaddr(A); printaddr(B); printaddr(C);
<span style="background-color:#e6b8af;">0x7f6f4c7a41f0</span>
<span style="background-color:#a4c2f4;">0x7f6f4c7b6810</span>
<span style="background-color:#00ff00;">0x7f6f4c7b69b0</span>

>> printmem(getaddr(A), 32)
<span style="background-color:#00ff00;">b0 69 7b 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#a4c2f4;">10 68 7b 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00

>> printmem(getaddr(B), 32)
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#00ff00;">b0 69 7b 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00

>> printmem(getaddr(C), 32)
<span style="background-color:#a4c2f4;">10 68 7b 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
</pre><p></p><p>So it turns out that Matlab keeps track of a set of linked variables with a kind of cyclical, doubly-linked list structure; array A is linked to B in the forward direction and is also linked to C in the reverse direction by looping back around, etc.  The cyclical nature of this makes sense, as we need to be able to start from any of A, B, or C and find all the linked arrays.  But it is still not entirely clear why the list needs to be cyclical AND linked in both directions.  In fact, in earlier versions of Matlab this cyclical list was only singly-linked.</p><h3 id="Conclusions">Conclusions</h3><p>Obviously there is a lot more to <code>mxArray</code> and Matlab internals than what we have delved into here.  Still, with this basic introduction I hope to have whet your appetite for understanding more about Matlab internals, and provided some simple tools to help you explore.  I want to reiterate that in general MathWorks's approach of an opaque <code>mxArray</code> type with access abstracted through an API layer is a good policy.  The last thing you would want to do is take the information here and write a bunch of code that relies on the structure of <code>mxArray</code> to work; next time MathWorks needs to add a new feature and change <code>mxArray</code>, all your code will break.  So in general we are all better off playing within the API that MathWorks provides.  And remember: poking into memory can crash your computer, so save your data!</p><p>On the other hand, occasionally there are cases, like in-place editing, where it is useful to push the capabilities of Matlab a little beyond what MathWorks envisioned.  In these cases, having an understanding of Matlab's internals can be critical, for example in understanding how to avoid conflicting with copy-on-write.  Therefore I hope the information presented here will prove useful.  Ideally, someone will be motivated to take this starting point and repair some of the tools like <i>headerdump</i> that made Matlab's internal workings more transparent in the past.  I believe that having more of this information out in the Matlab community is good for the community as a whole.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/' rel='bookmark' title='Matlab mex in-place editing'>Matlab mex in-place editing</a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Matlab mex in-place editing</title><link>http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/</link> <comments>http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/#comments</comments> <pubDate>Wed, 08 Feb 2012 17:00:25 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Mex]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[Peter Li]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2699</guid> <description><![CDATA[Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/' rel='bookmark' title='Matlab&#8217;s internal memory representation'>Matlab&#8217;s internal memory representation</a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome Matlab Mex power-user <a
target="_blank" rel="nofollow" href="http://absurdlycertain.blogspot.com/">Peter Li</a> to a first in a short series of articles about undocumented aspects of Mex programing</i></p><p>Editing Matlab arrays in-place can be an important technique for optimizing calculations, especially when handling data that use large blocks of memory.  The Matlab language itself has some <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/">limited support for in-place editing</a>, but when we are really concerned with speed we often turn to writing C/C++ extensions using the Mex interface.  Unfortunately, editing arrays in-place from Mex extensions is not officially supported in Matlab, and doing it incorrectly can cause data inconsistencies or can even cause Matlab to crash.  In this article, I will introduce the problem and show a simple solution that exhibit the basic implementation details of Matlab&#8217;s internal copy-on-write mechanism.</p><h3 id="Motivation">Why edit in-place?</h3><p>To demonstrate the techniques in this article, I use the <i>fast_median</i> function, which is part of <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/29453-nthelement">my nth_element package</a> on Matlab&#8217;s File Exchange.  You can download the package and play with the code if you want.  The examples are fairly self-explanatory, so if you do not want to try the code you should be okay just following along.</p><p>Let us try a few function calls to see how editing in-place can save time and memory:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #0000FF;">rand</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
&gt;&gt; <span style="color: #0000FF;">tic</span>; <span style="color: #0000FF;">median</span><span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>    
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">4.122654</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; fast_median<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">1.646448</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; fast_median_ip<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.927898</span> seconds.</pre></div></div><p>If you try running this, be careful not to make A too large; tune the example according to the memory available on your system. In terms of the execution time for the different functions, your mileage may vary depending on factors such as: your system, what Matlab version you are running, and whether your test data is arranged in a single vector or a multicolumn array.</p><p>This example illustrates a few general points: first, <i>fast_median</i> is significantly faster than Matlab&#8217;s <i><b>native</b></i> median function. This is because <i>fast_median</i> uses a more efficient algorithm; see the nth_element page for more details.  Besides being a shameless plug, this demonstrates why we might want to write a Mex function in the first place: rewriting the median function in pure Matlab would be slow, but using C++ we can significantly improve on the status quo.</p><p>The second point is that the in-place version, <i>fast_median_ip</i>, yields an additional speed improvement.  What is the difference?  Let us look behind the scenes; here are the CPU and memory traces from my system monitor after running the above:</p><p><center><div
class="wp-caption alignleft" style="width: 387px"><img
alt="Memory and CPU usage for median() vs. fast_median_ip()" src="http://UndocumentedMatlab.com/images/median_vs_fast_median_ip.png" title="Memory and CPU usage for median() vs. fast_median_ip()" width="377" height="425"/><p
class="wp-caption-text">Memory and CPU usage for <i><b>median</b></i> vs. <i>fast_median_ip</i></p></div></center></p><p>You can see four spikes in CPU use, and some associated changes in memory allocation:</p><p>The first spike in CPU is when we created the test data vector; memory use also steps up at that time.</p><p>The second CPU spike is the largest; that is Matlab&#8217;s median function.  You can see that over that period memory use stepped up again, and then stepped back down; the median function makes a copy of the entire input data, and then throws its copy away when it is finished; this is expensive in terms of time and resources.</p><p>The <i>fast_median</i> function is the next CPU spike; it has a similar step up and down in memory use, but it is much faster.</p><p>Finally, in the case of <i>fast_median_ip</i> we see something different; there is a spike in CPU use, but memory use stays flat; the in-place version is faster and more memory efficient because it does not make a copy of the input data.</p><div
class="" style="width: 100%; overflow: auto;"></div><p>There is another important difference with the in-place version; it modifies its input array.  This can be demonstrated simply:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = randi<span style="color: #080;">&#40;</span><span style="color: #33f;">100</span>, <span style="color: #080;">&#91;</span><span style="color: #33f;">10</span> <span style="color: #33f;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">39</span>    <span style="color: #33f;">42</span>    <span style="color: #33f;">98</span>    <span style="color: #33f;">25</span>    <span style="color: #33f;">64</span>    <span style="color: #33f;">75</span>     <span style="color: #33f;">6</span>    <span style="color: #33f;">56</span>    <span style="color: #33f;">71</span>    <span style="color: #33f;">89</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">median</span><span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">60</span>
&nbsp;
&gt;&gt; fast_median<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">60</span>
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">39</span>    <span style="color: #33f;">42</span>    <span style="color: #33f;">98</span>    <span style="color: #33f;">25</span>    <span style="color: #33f;">64</span>    <span style="color: #33f;">75</span>     <span style="color: #33f;">6</span>    <span style="color: #33f;">56</span>    <span style="color: #33f;">71</span>    <span style="color: #33f;">89</span>
&nbsp;
&gt;&gt; fast_median_ip<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">60</span>
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">39</span>     <span style="color: #33f;">6</span>    <span style="color: #33f;">25</span>    <span style="color: #33f;">42</span>    <span style="color: #33f;">56</span>    <span style="color: #33f;">64</span>    <span style="color: #33f;">75</span>    <span style="color: #33f;">71</span>    <span style="color: #33f;">98</span>    <span style="color: #33f;">89</span></pre></div></div><p>As you can see, all three methods get the same answer, but <i><b>median</b></i> and <i>fast_median</i> do not modify A in the workspace, whereas after running <i>fast_median_ip</i>, input array A has changed.  This is how the in-place method is able to run without using new memory; it operates on the existing array rather than making a copy.</p><h3 id="Pitfalls">Pitfalls with in-place editing</h3><p>Modifying a function&#8217;s input is common in many languages, but in Matlab there are only a few special conditions under which this is officially sanctioned.  This is not necessarily a bad thing; many people feel that modifying input data is bad programming practice and makes code harder to maintain.  But as we have shown, it can be an important capability to have if speed and memory use are critical to an application.</p><p>Given that in-place editing is not officially supported in Matlab Mex extensions, what do we have to do to make it work?  Let us look at the normal, input-copying <i>fast_median</i> function as a starting point:</p><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> mexFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nlhs, mxArray <span style="color: #000040;">*</span>plhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>, <span style="color: #0000ff;">int</span> nrhs, <span style="color: #0000ff;">const</span> mxArray <span style="color: #000040;">*</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   mxArray <span style="color: #000040;">*</span>incopy <span style="color: #000080;">=</span> mxDuplicateArray<span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
   plhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> run_fast_median<span style="color: #008000;">&#40;</span>incopy<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div><p>This is a pretty simple function (I have taken out a few lines of boiler plate input checking to keep things clean).  It relies on helper function <i>run_fast_median</i> to do the actual calculation, so the only real logic here is copying the input array <code>prhs[0]</code>.  Importantly, <i>run_fast_median</i> edits its inputs in-place, so the call to <i>mxDuplicateArray</i> ensures that the Mex function is overall well behaved, i.e. that it does not change its inputs.</p><p>Who wants to be well behaved though?  Can we save time and memory just by taking out the input duplication step?  Let us try it:</p><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> mexFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nlhs, mxArray <span style="color: #000040;">*</span>plhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>, <span style="color: #0000ff;">int</span> nrhs, <span style="color: #0000ff;">const</span> mxArray <span style="color: #000040;">*</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   plhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> run_fast_median<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const_cast</span><span style="color: #000080;">&lt;</span>mxarray <span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>  <span style="color: #666666;">// &lt;/mxarray&gt;</span>
<span style="color: #008000;">&#125;</span></pre></div></div><p>Very bad behavior; note that we cast the original <code>const mxArray*</code> input to a <code>mxArray*</code> so that the compiler will let us mess with it; naughty.</p><p>But does this accomplish edit in-place for <i>fast_median</i>?  Be sure to save any work you have open and then try it:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; mex fast_median_tweaked.<span style="">cpp</span>
&gt;&gt; A = randi<span style="color: #080;">&#40;</span><span style="color: #33f;">100</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">10</span> <span style="color: #33f;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; fast_median_tweaked<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">43</span></pre></div></div><p>Hmm, it looks like this worked fine.  But in fact there are subtle problems:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = randi<span style="color: #080;">&#40;</span><span style="color: #33f;">100</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">10</span> <span style="color: #33f;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">65</span>    <span style="color: #33f;">92</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">41</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>     <span style="color: #33f;">2</span>
&gt;&gt; B = A;
&gt;&gt; B'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">65</span>    <span style="color: #33f;">92</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">41</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>     <span style="color: #33f;">2</span>
&nbsp;
&gt;&gt; fast_median_tweaked<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">43</span>
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">2</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">41</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">65</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>    <span style="color: #33f;">92</span>
&gt;&gt; B'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">2</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">41</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">65</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>    <span style="color: #33f;">92</span></pre></div></div><p>Uhoh, spooky; we expected that running <i>fast_median_tweaked</i> would change input A, but somehow it has also changed B, even though B is supposed to be an independent copy.  Not good.  In fact, under some conditions this kind of uncontrolled editing in-place can crash the entire Matlab environment with a segfault.  What is going on?</p><h3 id="COW">Matlab&#8217;s copy-on-write mechanism</h3><p>The answer is that our simple attempt to edit in-place conflicts with Matlab&#8217;s internal copy-on-write mechanism.  Copy-on-write is an optimization built into Matlab to help avoid expensive copying of variables in memory (actually similar to what we are trying to accomplish with edit in-place).  We can see copy-on-write in action with some simple tests:</p><div
class="wp-caption alignright" style="width: 403px"><img
alt="Matlab's Copy-on-Write memory and CPU usage" src="http://UndocumentedMatlab.com/images/copy-on-write.png" title="Matlab's Copy-on-Write memory and CPU usage" width="393" height="466"/><p
class="wp-caption-text">Matlab's Copy-on-Write memory and CPU usage</p></div><div><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Test #1: update, then copy</span>
&gt;&gt; <span style="color: #0000FF;">tic</span>; A = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.588937</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000008</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; B = A; <span style="color: #0000FF;">toc</span>   
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000020</span> seconds.
&nbsp;
<span style="color: #228B22;">% Test #2: copy, then update</span>
&gt;&gt; <span style="color: #0000FF;">clear</span>
&gt;&gt; <span style="color: #0000FF;">tic</span>; A = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.588937</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; B = A; <span style="color: #0000FF;">toc</span>   
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000020</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.678160</span> seconds.</pre></div></div></div><p>In the first set of operations, time and memory are used to create A, but updating A and &#8220;copying&#8221; A into B take no memory and essentially no time.  This may come as a surprise since supposedly we have made an independent copy of A in B; why does creating B take no time or memory when A is clearly a large, expensive block?</p><p>The second set of operations makes things more clear.  In this case, we again create A and then copy it to B; again this operation is fast and cheap.  But assigning into A at this point takes time and consumes a new block of memory, even though we are only assigning into a single index of A.  This is copy-on-write: Matlab tries to save you from copying large blocks of memory unless you need to.  So when you first assign B to equal A, nothing is copied; the variable B is simply set to point to the same memory location already used by A.  Only after you try to change A (or B), does Matlab decide that you really need to have two copies of the large array.</p><p>There are some additional tricks Matlab does with copy-on-write.  Here is another example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">clear</span>
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span> = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.573240</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span> = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.560369</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; B = A; <span style="color: #0000FF;">toc</span>                     
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000016</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>               
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.690690</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.695758</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000011</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000004</span> seconds.</pre></div></div><p>This shows that for the purposes of copy-on-write, different elements of cell array A are treated independently.  When we assign B equal to A, nothing is copied.  Then when we change any part of A{1}, that whole element must be copied over.  When we subsequently change A{2}, that whole element must also be copied over; it was not copied earlier.  At this point, A and B are truly independent of each other, as both elements have experienced copy-on-write, so further assignments into either A or B are fast and require no additional memory.</p><p>Try playing with some struct arrays and you will find that copy-on-write also works independently for the elements of structs.</p><h3 id="mxUnshareArray">Reconciling edit in-place with copy-on-write: mxUnshareArray</h3><p>Now it is clear why we cannot simply edit arrays in-place from Mex functions; not only is it naughty, it fundamentally conflicts with copy-on-write.  Naively changing an array in-place can inadvertently change other variables that are still waiting for a copy-on-write, as we saw above when <i>fast_median_tweaked</i> inadvertently changed B in the workspace. This is, in the best case, an unmaintainable mess.  Under more aggressive in-place editing, it can cause Matlab to crash with a segfault.</p><p>Luckily, there is a simple solution, although it requires calling internal, undocumented Matlab functions.</p><p>Essentially what we need is a Mex function that can be run on a Matlab array that will do the following:</p><ol><li>Check whether the current array is sharing data with any other arrays that are waiting for copy-on-write.</li><li>If the array is shared, it must be unshared; the underlying memory must be copied and all the relevant pointers need to be fixed so that the array we want to work on is no longer accessible by anyone else.</li><li>If the array is not currently shared, simply proceed; the whole point is to avoid copying memory if we do not need to, so that we can benefit from the efficiencies of edit in-place.</li></ol><p>If you think about it, this is exactly the operation that Matlab needs to run internally when it is deciding whether an assignment operation requires a copy-on-write.  So it should come as no surprise that such a Mex function already exists in the form of a Matlab internal called <i>mxUnshareArray</i>.  Here is how you use it:</p><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">extern</span> <span style="color: #FF0000;">&quot;C&quot;</span> <span style="color: #0000ff;">bool</span> mxUnshareArray<span style="color: #008000;">&#40;</span>mxArray <span style="color: #000040;">*</span>array_ptr, <span style="color: #0000ff;">bool</span> noDeepCopy<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">void</span> mexFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nlhs, mxArray <span style="color: #000040;">*</span>plhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>, <span style="color: #0000ff;">int</span> nrhs, <span style="color: #0000ff;">const</span> mxArray <span style="color: #000040;">*</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   mxUnshareArray<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const_cast</span><span style="color: #000080;">&lt;</span>mxarray <span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>, <span style="color: #0000ff;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>  <span style="color: #666666;">//&lt;/mxarray&gt;</span>
   plhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> run_fast_median<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const_cast</span><span style="color: #000080;">&lt;</span>mxarray <span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>  <span style="color: #666666;">//&lt;/mxarray&gt;</span>
<span style="color: #008000;">&#125;</span></pre></div></div><p>This is the method actually used by <i>fast_median_ip</i> to efficiently edit in-place without risking conflicts with copy-on-write.  Of course, if the array turns out to need to be unshared, then you do not get the benefit of edit in-place because the memory ends up getting copied.  But at least things are safe and you get the in-place benefit as long as the input array is not being shared.</p><h3 id="Extra">Further topics</h3><p>The method shown here should allow you to edit normal Matlab numerical or character arrays in-place from Mex functions safely.  For a Mex function in C rather than C++, omit the &#8220;C&#8221; in the <code>extern</code> declaration and of course you will have to use C-style casting rather than <code>const_cast</code>.  If you need to edit cell or struct arrays in-place, or especially if you need to edit subsections of shared cell or struct arrays safely and efficiently while leaving the rest of the data shared, then you will need a few more tricks.  A good place to get started is <a
target="_blank" rel="nofollow" href="http://www.mk.tu-berlin.de/Members/Benjamin/mex_sharedArrays">this article by Benjamin Schubert</a>.</p><p>Unfortunately, over the last few years Mathworks seems to have decided to make it more difficult for users to access these kinds of internal methods to make our code more efficient.  So be aware of the risk that in some future version of Matlab this method will no longer work in its current form.</p><p>Ultimately much of what is known about <i>mxUnshareArray</i> as well as the internal implementation details of how Matlab keeps track of which arrays are shared goes back to the work of Peter Boettcher, particularly his <a
target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/c241d8821fb90275/">headerdump.c utility</a>.  Unfortunately, it appears that HeaderDump fails with Matlab releases >=R2010a, as Mathworks have changed some of the internal memory formats &#8211; perhaps some smart reader can pick up the work and adapt HeaderDump to the new memory format.</p><p>In a future article, I hope to discuss headerdump.c and its relevance for copy-on-write and edit in-place, and some other related tools for the latest Matlab releases that do not support HeaderDump.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/' rel='bookmark' title='Matlab&#8217;s internal memory representation'>Matlab&#8217;s internal memory representation</a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Controlling callback re-entrancy</title><link>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/</link> <comments>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/#comments</comments> <pubDate>Wed, 10 Aug 2011 18:00:57 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[GUI]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[COM]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Malcolm Lidierth]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2403</guid> <description><![CDATA[Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/continuous-slider-callback/' rel='bookmark' title='Continuous slider callback'>Continuous slider callback</a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li><li><a
href='http://undocumentedmatlab.com/blog/controlling-plot-data-tips/' rel='bookmark' title='Controlling plot data-tips'>Controlling plot data-tips</a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I&#8217;d like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King&#8217;s College London. Malcolm is well known in the Matlab-Java community for his <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15580-using-java-swing-components-in-matlab">jcontrol utility</a>. Some months ago, I mentioned his work on another File Exchange contribution, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilities">MUtilities</a> when I discussed <a
target="_blank" href="http://undocumentedmatlab.com/blog/transparent-matlab-figure-window/">transparent Matlab figure windows</a>. Today, Malcolm discusses one of his lesser-known but extremely important <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">isMultipleCall utility</a>.</i></p><p>Every now and again, a very simple bit of code turns out to be more useful than the author initially imagined. Something I have repeatedly used is the <i><b>isMultipleCall</b></i> function which I <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">posted</a> to MATLAB Central&#8217;s File Exchange a year or so ago.</p><p>The <i><b>isMultipleCall</b></i> function uses fully-documented pure-MATLAB to extend the control that can be achieved over callbacks.</p><p>Here was the problem: I had a modular system built in MATLAB which allowed third-party developers to add their own plugins. I wanted a mechanism to force the dismissal (&#8220;bail-out&#8221;) of a callback even when the <b>Interruptible</b> property of the parent object was set to &#8216;on&#8217;. Such callback re-entrancy issues are common for rapidly-firing events, and debugging and fixing them is usually <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/5809-how-to-implement-a-speed-limit-for-gui-button-press">not easy</a>.</p><p>The callback&#8217;s dismissal code would need to be fast because it might be called many dozens of times, e.g. in a <b>WindowButtonMotion</b> callback. An obvious approach was to check the function call stack using MATLAB&#8217;s <i><b>dbstack</b></i> function. Although, at first, this seemed likely to be too slow, profiling showed it was not – taking &lt; 40&micro;sec per call &#8211; and within a <b>WindowButtonMotion</b> callback in a real GUI, I could not perceive any slowing of the code.</p><p>Here is the function:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> <span style="color: #0000FF;">flag</span>=isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
  <span style="color: #0000FF;">flag</span> = <span style="color: #0000FF;">false</span>; 
  <span style="color: #228B22;">% Get the stack</span>
  s = <span style="color: #0000FF;">dbstack</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">if</span> numel<span style="color: #080;">&#40;</span>s<span style="color: #080;">&#41;</span>&lt; =<span style="color: #33f;">2</span>
    <span style="color: #228B22;">% Stack too short for a multiple call</span>
    <span style="color: #0000FF;">return</span>
  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #228B22;">% How many calls to the calling function are in the stack?</span>
  names = <span style="color: #080;">&#123;</span>s<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span>.<span style="">name</span><span style="color: #080;">&#125;</span>;
  TF = <span style="color: #0000FF;">strcmp</span><span style="color: #080;">&#40;</span>s<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">name</span>,names<span style="color: #080;">&#41;</span>;
  count = <span style="color: #0000FF;">sum</span><span style="color: #080;">&#40;</span>TF<span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">if</span> count&gt;<span style="color: #33f;">1</span>
    <span style="color: #228B22;">% More than 1</span>
    <span style="color: #0000FF;">flag</span> = <span style="color: #0000FF;">true</span>; 
  <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>With <i><b>isMultipleCall</b></i> invoked from another function (see note below), <i><b>dbstack</b></i> will return a structure with a minimum of 2 elements – the first relating to <i><b>isMultipleCall</b></i> itself and the second to the calling function. So with <i><b>numel</b></i>(s) &lt;= 2, there can be no multiple calls and we can return false immediately thus saving time in doing any further testing.  For <i><b>numel</b></i>(s) &gt; 2 we simply check to see whether the calling functions referenced in s(2) appears anywhere else on the stack. If it does, then we return true; otherwise false.</p><p>Then, in our callback code we simply use:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span></pre></div></div><p>If this line is placed first in the callback function code, it essentially mimics the behavior that you might expect after setting the <b>Interruptible</b> property of the event firing object to &#8216;off&#8217;. Adding a <i><b>drawnow()</b></i> at the end of the callback will ensure that any waiting callbacks in the queue are dismissed:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> MyCallback<span style="color: #080;">&#40;</span>hObj, EventData<span style="color: #080;">&#41;</span>
  <span style="color: #228B22;">% Quick bail-out if callback code is called before another has ended</span>
  <span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #F0F;">...</span>  <span style="color: #228B22;">% do some actual callback work here</span>
  <span style="color: #0000FF;">drawnow</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>There are several ways in which <i><b>isMultipleCall</b></i> can extend the standard MALAB functionality. First, by moving <i><b>isMultipleCall</b></i> reference from the first line of the callback we can create both an interruptible and an uninteruptible code block, e.g.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> MyCallback<span style="color: #080;">&#40;</span>hObj, EventData<span style="color: #080;">&#41;</span>
&nbsp;
  <span style="color: #228B22;">%Code Block 1</span>
  <span style="color: #F0F;">...</span>
&nbsp;
  <span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #228B22;">%Code Block 2</span>
  <span style="color: #F0F;">...</span>
&nbsp;
  <span style="color: #0000FF;">drawnow</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Second, as <i><b>isMultipleCall</b></i> controls the callbacks  &#8211; not the objects that trigger them &#8211; we can individually control the callbacks of objects which fire multiple events. That is particularly useful with Java components, which gives a third extension – <i><b>isMultipleCall</b></i> can be used in any function: not just the callbacks of standard MATLAB components, but also of Java or COM components.<br
/>  <br
/> Finally, as the callback, not the object is being controlled, we can control a callback that may be shared between multiple objects e.g. a menu component and a toolbar button.</p><p>Not bad for 13 lines of code.</p><p>Note: <i><b>isMultipleCall</b></i> must be called from a function, not from a string in the callback property.</p><p>Do you have any other favorite mechanism for controlling callback re-entrancy? If so, please <a
href="http://UndocumentedMatlab.com/blog/controlling-callback-re-entrancy/#respond">post a comment</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/continuous-slider-callback/' rel='bookmark' title='Continuous slider callback'>Continuous slider callback</a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li><li><a
href='http://undocumentedmatlab.com/blog/controlling-plot-data-tips/' rel='bookmark' title='Controlling plot data-tips'>Controlling plot data-tips</a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>JBoost &#8211; Integrating an external Java library in Matlab</title><link>http://undocumentedmatlab.com/blog/jboost-integrating-an-external-java-library-in-matlab/</link> <comments>http://undocumentedmatlab.com/blog/jboost-integrating-an-external-java-library-in-matlab/#comments</comments> <pubDate>Wed, 29 Jun 2011 18:00:58 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Adam Chapman]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2357</guid> <description><![CDATA[This article shows how an external Java library can be integrated in Matlab<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome guest blogger Adam Chapman, who has recently started a dedicated Matlab blog at <a
target="_blank" rel="nofollow" href="http://intelilab.blogspot.com/">http://intelilab.blogspot.com/</a>. Today, Adam shares his experience in integrating a 3rd-party Java library &#8211; in this case, the open-source JBoost library, in a Matlab application.</i></p><p>I had received a couple of requests asking me to create <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Alternating_decision_tree">alternating decision trees</a> (ADTs) in Matlab. Due to the self-organising nature of an ADT structure, it would be an extremely slow and frustrating task to code up an ADT building algorithm in any language.</p><p>I was cautious of looking for source code that would do the job for me, as I was concerned that interfacing external code with Matlab would be another difficult task.</p><p>I had interfaced external VBA and C++ code with Matlab before, but never attempted interfacing Java code. I remember all of those previous interfacing projects being a nightmare to debug and very tricky to code into a stable solution. After some hesitation I decided that I would give the open-source <a
target="_blank" rel="nofollow" href="http://jboost.sourceforge.net/">Jboost library</a> a try.</p><p>It <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f98533.html">turns out</a> that <i>&#8220;every Matlab installation includes a Java Virtual Machine (JVM), so that you can use the Java interpreter via MATLAB commands, and you can create and run programs that create and access Java objects&#8221;</i>.</p><p>That&#8217;s all very well, but I needed to know exactly how I should call the <code>main()</code> function in Jboost directly from Matlab. In this Article I&#8217;ll explain how I replicated <a
target="_blank" rel="nofollow" href="http://jboost.sourceforge.net/examples.html">the example walkthrough on the Jboost website</a>, using the spambase data set as an example.</p><p>Reading the Jboost <a
target="_blank" rel="nofollow" href="http://jboost.sourceforge.net/install.html">installation notes</a>, I found that three paths need to be added to the Java class path. Instead of adding a system environment variable like the Jboost <a
target="_blank" rel="nofollow" href="http://jboost.sourceforge.net/doc.html">documentation</a> suggests, we can simply use the Matlab&#8217;s built-in <i><b>javaaddpath</b></i> function:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">JBOOST_DIR=<span style="color:#A020F0;">'C:\Users\Adam\Desktop\JBOOST\jboost-2.2\jboost-2.2'</span>;
&nbsp;
newpath1=<span style="color: #080;">&#91;</span>JBOOST_DIR <span style="color:#A020F0;">'\dist\jboost.jar'</span><span style="color: #080;">&#93;</span>;
newpath2=<span style="color: #080;">&#91;</span>JBOOST_DIR <span style="color:#A020F0;">'\lib\jfreechart-1.0.10.jar'</span><span style="color: #080;">&#93;</span>;
newpath3=<span style="color: #080;">&#91;</span>JBOOST_DIR <span style="color:#A020F0;">'\lib\jcommon-1.0.8.jar'</span><span style="color: #080;">&#93;</span>;
&nbsp;
<span style="color: #228B22;">% add Jboost classes to javaclasspath</span>
javaaddpath<span style="color: #080;">&#40;</span>newpath1<span style="color: #080;">&#41;</span>
javaaddpath<span style="color: #080;">&#40;</span>newpath2<span style="color: #080;">&#41;</span>
javaaddpath<span style="color: #080;">&#40;</span>newpath3<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">% also add JBOOST_DIR to the matlab path so that matlab can look there for non-jave code and data files:</span>
<span style="color: #0000FF;">addpath</span><span style="color: #080;">&#40;</span>JBOOST_DIR<span style="color: #080;">&#41;</span></pre></div></div><p>we can check those paths were added by reading back the dynamic java classpath:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; javaclasspath<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'-dynamic'</span><span style="color: #080;">&#41;</span>
&nbsp;
DYNAMIC JAVA <span style="color: #0000FF;">PATH</span>
C<span style="color: #F0F;">:</span>\Users\Adam\Desktop\JBOOST\jboost-<span style="color: #33f;">2.2</span>\jboost-<span style="color: #33f;">2.2</span>\lib\jcommon-1.0.8.<span style="">jar</span>    
C<span style="color: #F0F;">:</span>\Users\Adam\Desktop\JBOOST\jboost-<span style="color: #33f;">2.2</span>\jboost-<span style="color: #33f;">2.2</span>\lib\jfreechart-1.0.10.<span style="">jar</span>
C<span style="color: #F0F;">:</span>\Users\Adam\Desktop\JBOOST\jboost-<span style="color: #33f;">2.2</span>\jboost-<span style="color: #33f;">2.2</span>\dist\jboost.<span style="">jar</span></pre></div></div><p>Now I had the paths set up for Matlab and the JVM to find code and files in, I had to work out how to actually run the Jboost <code>main()</code> function.</p><p>Matlab&#8217;s <i><b>methodsview</b></i> function lists information on the methods in a Java class:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">methodsview<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'jboost.controller.Controller'</span><span style="color: #080;">&#41;</span></pre></div></div><p>pops a new window, from which we can derive that the main function for Jboost expects a <code>java.lang.String</code> array object (which is standard for a <code>main()</code> function in Java):</p><p><center><div
class="wp-caption aligncenter" style="width: 610px"><a
target="_blank" href="http://UndocumentedMatlab.com/images/JBoost_methodsview.png"><img
alt="View of JBoost's class function using methodsview (click for details)" src="http://UndocumentedMatlab.com/images/JBoost_methodsview.png" title="View of JBoost's class function using methodsview (click for details)" width="600" /></a><p
class="wp-caption-text">View of JBoost's class function using <i><b>methodsview</b></i> (click for details)</p></div></center></p><p>(we could also have used Yair&#8217;s <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">UIINSPECT utility</a> on the File Exchange, to display even more information on the Java class&#8217;s methods, callbacks and properties, but for our simple usage here, the built-in <i><b>methodsview</b></i> function is sufficient)</p><p>To build a Java string array to input to Jboost, we use the built-in <i><b>java_array</b></i> function:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">strArray = java_array<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'java.lang.String'</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
strArray<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = java.<span style="">lang</span>.<span style="">String</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'-S'</span><span style="color: #080;">&#41;</span>;
strArray<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span> = java.<span style="">lang</span>.<span style="">String</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'C:\Users\Adam\Desktop\JBOOST\jboost-2.2\jboost-2.2\demo\spambase'</span><span style="color: #080;">&#41;</span>; 
strArray<span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span> = java.<span style="">lang</span>.<span style="">String</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'-CONFIG'</span><span style="color: #080;">&#41;</span>;
strArray<span style="color: #080;">&#40;</span><span style="color: #33f;">4</span><span style="color: #080;">&#41;</span> = java.<span style="">lang</span>.<span style="">String</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'spambase.config'</span><span style="color: #080;">&#41;</span>;
strArray<span style="color: #080;">&#40;</span><span style="color: #33f;">5</span><span style="color: #080;">&#41;</span> = java.<span style="">lang</span>.<span style="">String</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'-m'</span><span style="color: #080;">&#41;</span>;
strArray<span style="color: #080;">&#40;</span><span style="color: #33f;">6</span><span style="color: #080;">&#41;</span> = java.<span style="">lang</span>.<span style="">String</span><span style="color: #080;">&#40;</span>‘MATLABTREE.<span style="">m</span>'<span style="color: #080;">&#41;</span>;</pre></div></div><p>Note how I initialized it with a size of 1 element, and let it grow as new elements are added since the array is very small there is no need to worry about the time saved by pre-allocating. The first 2 elements define the directory that Jboost is to look for data files in, the next 2 define a standard Jboost configuration file and the final 2 elements are rather special: they define the name of the m-file that will contain automatically generated Matlab code, allowing us to use the decision tree in the future without going in and out of Java.</p><p>Alternately, we could have simply used Matlab&#8217;s cell-array, as in:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">strArray = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'-S'</span>, <span style="color:#A020F0;">'C:\...'</span>, <span style="color:#A020F0;">'-CONFIG'</span>, <span style="color:#A020F0;">'spambase.config'</span>, <span style="color:#A020F0;">'-m'</span>, <span style="color:#A020F0;">'MATLABTREE.m'</span><span style="color: #080;">&#125;</span>;</pre></div></div><p>Now to construct an Alternating Decision Tree with Jboost, just call the Java jboost class containing the <code>main()</code> function, and input the array of parameters that we just constructed:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% input the configuration class into the jboost controller</span>
jboost.<span style="">controller</span>.<span style="">Controller</span>.<span style="">main</span><span style="color: #080;">&#40;</span>strArray<span style="color: #080;">&#41;</span></pre></div></div><p>With all the code so far, Matlab will invoke the Java jboost libraries to train an ADT to detect spam emails based on their contents defined in the spambase dataset. You will see the verbose java print-outs in the Matlab command window while it is running.</p><p>The jBoost developers use a Perl script to create an image of the completed ADT. That is even easier to call from Matlab than the Java routines were:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">perl<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'atree2dot2ps_hi_res.pl'</span>,<span style="color:#A020F0;">'-d'</span>,<span style="color:#A020F0;">'C:\Users\Adam\Desktop\JBOOST\jboost-2.2\jboost-2.2\demo\'</span>,<span style="color:#A020F0;">'-s'</span>,<span style="color:#A020F0;">'spambase.spec'</span>,<span style="color:#A020F0;">'-i'</span>,<span style="color:#A020F0;">'spambase.info'</span>,<span style="color:#A020F0;">'-t'</span>,<span style="color:#A020F0;">'spambase.output.tree'</span><span style="color: #080;">&#41;</span></pre></div></div><p>Now if you look in the folder that you defined in the &#8220;-d&#8221; parameter above, you will see that the Perl script has created a few images of the tree in different formats.  The .png file is below. I think it is incredible that an inanimate machine can be programmed to have the intelligence to create something so intricate.</p><p><center><div
class="wp-caption aligncenter" style="width: 810px"><a
target="_blank" rel="nofollow" href="http://img31.imageshack.us/img31/952/spambase0.png"><img
alt="Resulting ADT tree (click for details)" src="http://img31.imageshack.us/img31/952/spambase0.png" title="Resulting ADT tree (click for details)" width="800" /></a><p
class="wp-caption-text">Resulting ADT tree (click for details)</p></div></center></p><p>During this small project I realized that calling Java and Perl classes from Matlab is actually pretty easy. However, calling python, which jboost uses for some post-processing routines is actually very hard. I&#8217;ve decided to create my own Matlab versions of the error and margin plotting functions that Jboost uses, and will add them to the sourceforge project as soon as I&#8217;m happy with them.</p><p>I&#8217;d like to thank Aaron Arvey and Yair Altman for their friendly support during this project.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/jboost-integrating-an-external-java-library-in-matlab/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>UDD Events and Listeners</title><link>http://undocumentedmatlab.com/blog/udd-events-and-listeners/</link> <comments>http://undocumentedmatlab.com/blog/udd-events-and-listeners/#comments</comments> <pubDate>Wed, 16 Mar 2011 18:43:16 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[UDD event listeners can be used to listen to property value changes and other important events of Matlab objects<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/detecting-window-focus-events/' rel='bookmark' title='Detecting window focus events'>Detecting window focus events</a> <small>Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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><pre> </pre>]]></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>.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> displayEventInfo<span style="color: #080;">&#40;</span>source, eventData<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%DISPLAYEVENTINFO display the classes of source, data objects</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   DISPLAYEVENTINFO(SOURCE, EVENTDATA) returns the classes</span>
<span style="color: #228B22;">%   of the source object and the event data object</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   INPUTS:</span>
<span style="color: #228B22;">%       SOURCE    : the event source</span>
<span style="color: #228B22;">%       EVENTDATA : the event data</span>
  <span style="color: #0000FF;">if</span> ~<span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>source<span style="color: #080;">&#41;</span>
    <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>, <span style="color:#A020F0;">'The source object class is: %s'</span>,<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>source<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">end</span>
  <span style="color: #0000FF;">if</span> ~<span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>eventData<span style="color: #080;">&#41;</span>
    <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>, <span style="color:#A020F0;">'The event data class is: %s'</span>,<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>eventData<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><h3 id="listener">Creating a listener</h3><p>In the section on <a
target="_blank" href="http://undocumentedmatlab.com/blog/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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">a = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'a'</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
hListener = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>a,<span style="color:#A020F0;">'simpleEvent'</span>,@displayEventInfo<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'listeners'</span>, hListener<span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">evtData = handle.<span style="">EventData</span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'simpleEvent'</span><span style="color: #080;">&#41;</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; a.<span style="">send</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simpleEvent'</span>, evtData<span style="color: #080;">&#41;</span>
The source object <span style="color: #0000FF;">class</span> <span style="color: #0000FF;">is</span><span style="color: #F0F;">:</span> simple.<span style="">object</span>
The event data <span style="color: #0000FF;">class</span> <span style="color: #0000FF;">is</span><span style="color: #F0F;">:</span> handle.<span style="">EventData</span></pre></div></div><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="http://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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> modifyAxesChildren<span style="color: #080;">&#40;</span>~, eventData<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%MODIFYAXESCHILDREN monitor and axis and modify added children</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   MODIFYAXESCHILDREN(SOURCE,EVENTDATA) is an event handler to</span>
<span style="color: #228B22;">%   change newly-added lines to green and remove added patches</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   INPUTS:</span>
<span style="color: #228B22;">%       EVENTDATA : handle.ChildEventData object</span>
   <span style="color: #0000FF;">switch</span> eventData.<span style="">Child</span>.<span style="">classhandle</span>.<span style="">Name</span>
      <span style="color: #0000FF;">case</span> <span style="color:#A020F0;">'line'</span>
         eventData.<span style="">Child</span>.<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Color'</span>, <span style="color:#A020F0;">'green'</span><span style="color: #080;">&#41;</span>;
         <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Color changed to green.'</span><span style="color: #080;">&#41;</span>
      <span style="color: #0000FF;">case</span> <span style="color:#A020F0;">'patch'</span>
         eventData.<span style="">Child</span>.<span style="color: #0000FF;">delete</span>;
         <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Patch removed.'</span><span style="color: #080;">&#41;</span>
   <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>Next create an axis, and a listener which is triggered when children are added:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% create a new axes and get its handle</span>
a = hg.<span style="color: #0000FF;">axes</span>;
&nbsp;
<span style="color: #228B22;">% create the listener</span>
listen = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'ObjectChildAdded'</span>, @modifyAxesChildren<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% add a line</span>
&gt;&gt; hg.<span style="color: #0000FF;">line</span>;
Color changed to green.
&nbsp;
<span style="color: #228B22;">% try to add a patch</span>
&gt;&gt; hg.<span style="color: #0000FF;">patch</span>;
<span style="color: #0000FF;">Patch</span> removed.</pre></div></div><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.</p><p>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.</p><p>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="http://undocumentedmatlab.com/blog/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).</p><p>Note that the <b><i>handle.listener</i></b> syntax is slightly different for property events:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hProp = <span style="color: #0000FF;">findprop</span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'Value'</span><span style="color: #080;">&#41;</span>;
hListener = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>a,hProp,<span style="color:#A020F0;">'PropertyPreGet'</span>,@displayEventInfo<span style="color: #080;">&#41;</span>;</pre></div></div><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.</p><p>To illustrate how this works we will create a Java Swing <code>JFrame</code> and listen for <code>MouseClicked</code> events:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Create the Java Frame</span>
javaFrame = javax.<span style="">swing</span>.<span style="">JFrame</span>;
javaFrame.<span style="">setSize</span><span style="color: #080;">&#40;</span><span style="color: #33f;">200</span>, <span style="color: #33f;">200</span><span style="color: #080;">&#41;</span>;
javaFrame.<span style="">show</span>;
&nbsp;
<span style="color: #228B22;">% Create a UDD peer for the new JFrame (two alternatives)</span>
javaFramePeer = javaFrame.<span style="">handle</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% alternative #1</span>
javaFramePeer = handle<span style="color: #080;">&#40;</span>javaFrame, <span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% alternative #2</span>
&nbsp;
<span style="color: #228B22;">% Create the a listener for the Java MouseClicked event</span>
listen = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>javaFramePeer, <span style="color:#A020F0;">'MouseClicked'</span>, @displayEventInfo<span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 210px"><img
alt="a simple Java Swing JFrame" src="http://UndocumentedMatlab.com/images/UDD_Java_Frame.png" title="a simple Java Swing JFrame" width="200" height="200" /><p
class="wp-caption-text">a simple Java Swing JFrame</p></div></center></p><p>When we click on the JFrame, our UDD peer triggers the callback:</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;">The source object <span style="color: #000000; font-weight: bold;">class</span> is<span style="color: #339933;">:</span> javahandle_withcallbacks.<span style="color: #006633;">javax</span>.<span style="color: #006633;">swing</span>.<span style="color: #003399;">JFrame</span>
The event data <span style="color: #000000; font-weight: bold;">class</span> is<span style="color: #339933;">:</span> handle.<span style="color: #006633;">JavaEventData</span></pre></div></div><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="http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/">details</a>).</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">clear</span> listen
javaFramePeer.<span style="">MouseClickedCallback</span> = @displayEventInfo</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">   <span style="color: #228B22;">% Property to hold our callback handle</span>
   prop = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'SimpleEventCallback'</span>, <span style="color:#A020F0;">'MATLAB callback'</span><span style="color: #080;">&#41;</span>;
   prop.<span style="">setFunction</span> = @setValue;
&nbsp;
   <span style="color: #228B22;">% hidden property to hold the listener for our callback</span>
   prop = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'SimpleEventListener'</span>, <span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#41;</span>;
   prop.<span style="">Visible</span> = <span style="color:#A020F0;">'off'</span>;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #0000FF;">function</span> propVal = setValue<span style="color: #080;">&#40;</span>self, value<span style="color: #080;">&#41;</span>
   <span style="color: #228B22;">%SETVALUE function to transfer function handle from callback property to listener</span>
   self.<span style="">SimpleEventListener</span>.<span style="">Callback</span> = value;
   propVal = value;
<span style="color: #0000FF;">end</span></pre></div></div><p>Next we add the following to our simple.object constructor file:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% set the hidden listener property to a handle.listener</span>
simpleObject.<span style="">SimpleEventListener</span> = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>simpleObject, <span style="color:#A020F0;">'simpleEvent'</span>, <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;</pre></div></div><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.</p><p>This series will conclude next week with a look at the special relationship between UDD and Java.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/detecting-window-focus-events/' rel='bookmark' title='Detecting window focus events'>Detecting window focus events</a> <small>Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/udd-events-and-listeners/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>UDD Properties</title><link>http://undocumentedmatlab.com/blog/udd-properties/</link> <comments>http://undocumentedmatlab.com/blog/udd-properties/#comments</comments> <pubDate>Wed, 09 Mar 2011 18:00:17 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[UDD provides a very convenient way to add customizable properties to existing Matlab object handles<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/borderless-button-used-for-plot-properties/' rel='bookmark' title='Borderless button used for plot properties'>Borderless button used for plot properties</a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li></ol><pre> </pre>]]></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.</p><p>As we have <a
target="_blank" href="http://undocumentedmatlab.com/blog/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).</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Create instance of simple.object</span>
&gt;&gt; a = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'a'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Find the Value property and list its meta-properties</span>
<span style="color: #228B22;">% We can manipulate these meta-properties within limits</span>
&gt;&gt; a.<span style="color: #0000FF;">findprop</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Value'</span><span style="color: #080;">&#41;</span>.<span style="color: #0000FF;">get</span>
            Name<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'Value'</span>
     Description<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
        DataType<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'single'</span>
    FactoryValue<span style="color: #F0F;">:</span> <span style="color: #33f;">7.3891</span>
     AccessFlags<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 <span style="color: #0000FF;">struct</span><span style="color: #080;">&#93;</span>
         Visible<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'on'</span>
     GetFunction<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
     SetFunction<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; prop.<span style="">Visible</span> = <span style="color:#A020F0;">'off'</span>;  <span style="color: #228B22;">% i.e. hidden property (see below)</span>
&gt;&gt; prop.<span style="">AccessFlags</span>.<span style="">PublicSet</span> = <span style="color:#A020F0;">'off'</span>;   <span style="color: #228B22;">% i.e. read-only</span>
&gt;&gt; prop.<span style="">AccessFlags</span>.<span style="">PublicGet</span> = <span style="color:#A020F0;">'on'</span>;
&nbsp;
<span style="color: #228B22;">% Find the DataType meta-property of the Value property</span>
<span style="color: #228B22;">% This meta-property and all other schema.prop base class properties are fixed</span>
&gt;&gt; a.<span style="color: #0000FF;">findprop</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Value'</span><span style="color: #080;">&#41;</span>.<span style="color: #0000FF;">findprop</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'DataType'</span><span style="color: #080;">&#41;</span>.<span style="color: #0000FF;">get</span>
            Name<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'DataType'</span>
     Description<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
        DataType<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'string'</span>
    FactoryValue<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
           <span style="color: #F0F;">...</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; p=schema.<span style="">prop</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'MyFavoriteBlog'</span>,<span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>
p =
	schema.<span style="">prop</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'MyFavoriteBlog'</span>,<span style="color:#A020F0;">'UndocumentedMatlab.com'</span><span style="color: #080;">&#41;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'MyFavoriteBlog'</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
UndocumentedMatlab.<span style="">com</span></pre></div></div><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="http://undocumentedmatlab.com/blog/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>).</p><p><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>obj, <span style="color:#A020F0;">'Value'</span>, <span style="color:#A020F0;">'abcd'</span><span style="color: #080;">&#41;</span>
??? Parameter must be scalar.
&nbsp;
&gt;&gt; obj.<span style="">Value</span>=<span style="color:#A020F0;">'abcd'</span>
??? Parameter must be scalar.
&nbsp;
&gt;&gt; obj.<span style="">Name</span>=<span style="color: #33f;">123</span>
??? Parameter must be a string.</pre></div></div><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>.</p><p>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.</p><p>Let&#8217;s use a <a
target="_blank" rel="nofollow" href="http://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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> tline = taggedLine<span style="color: #080;">&#40;</span><span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%TAGGEDLINE create a line with Editable property</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   TLINE = TAGGEDLINE(VARARGIN) create a new handle graphics line</span>
<span style="color: #228B22;">%   and add 'Ediatable' property to line. Default property value is 'yes'.</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   INPUTS:</span>
<span style="color: #228B22;">%       VARARGIN  : property value pairs to pass to line</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   OUTPUTS:</span>
<span style="color: #228B22;">%       TLINE     : hg line object with Editable property</span>
&nbsp;
    <span style="color: #228B22;">% If undefined define yes/no datatype&lt;/font&gt;</span>
    <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>findtype<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'yes/no'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
        schema.<span style="">EnumType</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'yes/no'</span>, <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'yes'</span>, <span style="color:#A020F0;">'no'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
    tline = <span style="color: #0000FF;">line</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    schema.<span style="">prop</span><span style="color: #080;">&#40;</span>tline, <span style="color:#A020F0;">'Editable'</span>, <span style="color:#A020F0;">'yes/no'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%SCHEMA  hg package definition function</span>
    schema.<span style="">package</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hg'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>We create our class definition as a subclass of the handle graphics line class:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%SCHEMA  hg.taggedline class definition function</span>
    <span style="color: #228B22;">% package definition</span>
    superPackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hg'</span><span style="color: #080;">&#41;</span>;
    pkg = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hg'</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% class definition</span>
    c = schema.<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>pkg, <span style="color:#A020F0;">'taggedline'</span>, findclass<span style="color: #080;">&#40;</span>superPackage, <span style="color:#A020F0;">'line'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>findtype<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'yes/no'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
        schema.<span style="">EnumType</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'yes/no'</span>, <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'yes'</span>, <span style="color:#A020F0;">'no'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
&nbsp;
    <span style="color: #228B22;">% add properties to class</span>
    schema.<span style="">prop</span><span style="color: #080;">&#40;</span>c, <span style="color:#A020F0;">'Editable'</span>, <span style="color:#A020F0;">'yes/no'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>And our constructor is:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> self = taggedline
<span style="color: #228B22;">%OBJECT constructor for the simple.object class</span>
    self = hg.<span style="">taggedline</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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.</p><p>The <code>schema.UserType</code> has the following constructor syntax:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">schema.<span style="">UserType</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'newTypeName'</span>, <span style="color:#A020F0;">'baseTypeName'</span>, typeCheckFunctionHandle<span style="color: #080;">&#41;</span></pre></div></div><p>For example, to create a user-defined type for unsigned eight-bit integers we might use the following code:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">schema.<span style="">UserType</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'uint8'</span>, <span style="color:#A020F0;">'short'</span>, @check_uint8<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #0000FF;">function</span> check_uint8<span style="color: #080;">&#40;</span>value<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%CHECK_UINT8 Check function for uint8 type definition</span>
    <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>value<span style="color: #080;">&#41;</span> <span style="color: #F0F;">||</span> <span style="color: #080;">&#40;</span>value &lt; <span style="color: #33f;">0</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">||</span> <span style="color: #080;">&#40;</span>value &gt; <span style="color: #33f;">255</span><span style="color: #080;">&#41;</span>
        <span style="color: #0000FF;">error</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Value must be a scalar between 0 and 255'</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">for</span> prop = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>classhandle<span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'Properties'</span><span style="color: #080;">&#41;</span>'
       <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">strcmpi</span><span style="color: #080;">&#40;</span>prop.<span style="">Visible</span>,<span style="color:#A020F0;">'off'</span><span style="color: #080;">&#41;</span>, <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>prop.<span style="">Name</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">end</span>
   <span style="color: #0000FF;">end</span>
&nbsp;
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></div></div><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="http://undocumentedmatlab.com/blog/tag/hidden-property/">described in this website</a>.</p><p>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.</p><p><b>GetFunction</b> and <b>SetFunction</b> were described in last week&#8217;s article, <a
href="http://undocumentedmatlab.com/blog/hierarchical-systems-with-udd/">Creating a UDD Hierarchy</a>.</p><p><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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; a = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'a'</span><span style="color: #080;">&#41;</span>;
&gt;&gt; a.<span style="">n</span>  <span style="color: #228B22;">% abbreviation of Name</span>
<span style="color: #0000FF;">ans</span> =
a
&nbsp;
&gt;&gt; a.<span style="">v</span>  <span style="color: #228B22;">% abbreviation of Value</span>
<span style="color: #0000FF;">ans</span> =
    <span style="color: #33f;">0.0000</span></pre></div></div><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;</p><p><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></p><p>In the next installment of this series we will take a look at UDD events and listeners.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/borderless-button-used-for-plot-properties/' rel='bookmark' title='Borderless button used for plot properties'>Borderless button used for plot properties</a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/udd-properties/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Hierarchical Systems with UDD</title><link>http://undocumentedmatlab.com/blog/hierarchical-systems-with-udd/</link> <comments>http://undocumentedmatlab.com/blog/hierarchical-systems-with-udd/#comments</comments> <pubDate>Wed, 02 Mar 2011 18:00:25 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[UDD objects can be grouped in structured hierarchies - this article explains how<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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><pre> </pre>]]></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></p><p>We have looked at the <a
target="_blank" href="http://undocumentedmatlab.com/blog/introduction-to-udd/">tools for working with UDD classes</a>, and <a
target="_blank" href="http://undocumentedmatlab.com/blog/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>.</p><p>We illustrate the technique by creating a hierarchy of <code>simple.object</code>s as shown in the following diagram:</p><p><center><div
class="wp-caption aligncenter" style="width: 210px"><img
alt="Sample UDD objects hierarchy" src="http://UndocumentedMatlab.com/images/UDD_structure.png" title="Sample UDD objects hierarchy" width="200" height="177" /><p
class="wp-caption-text">Sample UDD objects hierarchy</p></div></center></p><p>To begin we create five instances of the <code>simple.object</code> class from the previous article:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Remember that simple.object accepts a name and a value</span>
a = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'a'</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
b = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'b'</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
c = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'c'</span>, <span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>;
d = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'d'</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
e = simple.<span style="">object</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'e'</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>To form the structure we use the <i>connect</i> method. We can use either dot notation or the Matlab syntax:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Dot-notation examples:</span>
a.<span style="">connect</span><span style="color: #080;">&#40;</span>b, <span style="color:#A020F0;">'down'</span><span style="color: #080;">&#41;</span>;
b.<span style="">connect</span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'up'</span><span style="color: #080;">&#41;</span>;       <span style="color: #228B22;">% alternative to the above</span>
&nbsp;
<span style="color: #228B22;">% Matlab notation examples:</span>
connect<span style="color: #080;">&#40;</span>a, b, <span style="color:#A020F0;">'down'</span><span style="color: #080;">&#41;</span>;
connect<span style="color: #080;">&#40;</span>b, a, <span style="color:#A020F0;">'up'</span><span style="color: #080;">&#41;</span>;      <span style="color: #228B22;">% alternative to the above</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">b.<span style="">connect</span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'up'</span><span style="color: #080;">&#41;</span>;
c.<span style="">connect</span><span style="color: #080;">&#40;</span>b, <span style="color:#A020F0;">'left'</span><span style="color: #080;">&#41;</span>;
d.<span style="">connect</span><span style="color: #080;">&#40;</span>b, <span style="color:#A020F0;">'up'</span><span style="color: #080;">&#41;</span>;
e.<span style="">connect</span><span style="color: #080;">&#40;</span>d, <span style="color:#A020F0;">'left'</span><span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; b.<span style="">up</span>
<span style="color: #0000FF;">ans</span> =
  Name<span style="color: #F0F;">:</span> a
 Value<span style="color: #F0F;">:</span> <span style="color: #33f;">1.000000</span>
&nbsp;
&gt;&gt; b.<span style="">right</span>
<span style="color: #0000FF;">ans</span> =
  Name<span style="color: #F0F;">:</span> c
 Value<span style="color: #F0F;">:</span> <span style="color: #33f;">0.000000</span>
&nbsp;
&gt;&gt; b.<span style="">down</span>
<span style="color: #0000FF;">ans</span> =
  Name<span style="color: #F0F;">:</span> d
 Value<span style="color: #F0F;">:</span> <span style="color: #33f;">1.000000</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">objectArray = <span style="color: #0000FF;">find</span><span style="color: #080;">&#40;</span>startingNode, <span style="color:#A020F0;">'property'</span>, <span style="color:#A020F0;">'value'</span>, <span style="color: #F0F;">...</span><span style="color: #080;">&#41;</span></pre></div></div><p>To search from the top of our hierarchy for objects of type <code>simple.object</code> we would use:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">find</span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'-isa'</span>, <span style="color:#A020F0;">'simple.object'</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
        simple.<span style="">object</span><span style="color: #F0F;">:</span> <span style="color: #33f;">5</span>-by-<span style="color: #33f;">1</span>    <span style="color: #228B22;">% a, b, c, d, e</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">find</span><span style="color: #080;">&#40;</span>b, <span style="color:#A020F0;">'-isa'</span>, <span style="color:#A020F0;">'simple.object'</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
	simple.<span style="">object</span><span style="color: #F0F;">:</span> <span style="color: #33f;">3</span>-by-<span style="color: #33f;">1</span>    <span style="color: #228B22;">% b, d, e</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">find</span><span style="color: #080;">&#40;</span>a, <span style="color:#A020F0;">'-isa'</span>, <span style="color:#A020F0;">'simple.object'</span>, <span style="color:#A020F0;">'Value'</span>, <span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
  Name<span style="color: #F0F;">:</span> c
 Value<span style="color: #F0F;">:</span> <span style="color: #33f;">0.000000</span></pre></div></div><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="http://UndocumentedMatlab.com/blog/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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% class definition</span>
superPackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hg'</span><span style="color: #080;">&#41;</span>;
superClass = findclass<span style="color: #080;">&#40;</span>superPackage, <span style="color:#A020F0;">'uipanel'</span><span style="color: #080;">&#41;</span>;
simpleClass = schema.<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>simplePackage, <span style="color:#A020F0;">'object'</span>,superClass<span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">t = uitree<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'v0'</span>, <span style="color:#A020F0;">'root'</span>, a<span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">drawnow</span>;
t.<span style="">expand</span><span style="color: #080;">&#40;</span>t.<span style="">getRoot</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">drawnow</span>;
t.<span style="">expand</span><span style="color: #080;">&#40;</span>t.<span style="">getRoot</span>.<span style="">getFirstChild</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 451px"><img
alt="Simple structure presented in a Matlab uitree" src="http://UndocumentedMatlab.com/images/UDD_uitree_1.png" title="Simple structure presented in a Matlab uitree" width="441" height="189" /><p
class="wp-caption-text">Simple structure presented in a Matlab <i><b>uitree</b></i></p></div></center></p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'Type'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>;
p.<span style="">FactoryValue</span> = <span style="color:#A020F0;">'simple.object'</span>;</pre></div></div><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:</p><p><center><div
class="wp-caption aligncenter" style="width: 451px"><img
alt="Corrected node names for our UDD structure" src="http://UndocumentedMatlab.com/images/UDD_uitree_2.png" title="Corrected node names for our UDD structure" width="441" height="189" /><p
class="wp-caption-text">Corrected node names for our UDD structure</p></div></center></p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'Type'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>;
p.<span style="">GetFunction</span> = @getType;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> propVal = getType<span style="color: #080;">&#40;</span>self, value, prop<span style="color: #080;">&#41;</span>
   propVal = self.<span style="">Name</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Alternately, as a single one-liner in the schema definition file:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">p.<span style="">GetFunction</span> = @<span style="color: #080;">&#40;</span>self,value,prop<span style="color: #080;">&#41;</span> self.<span style="">Name</span>;</pre></div></div><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.</p><p>With these changes when we recreate our <i><b>uitree</b></i> we obtain:</p><p><center><div
class="wp-caption aligncenter" style="width: 451px"><img
alt="Overloaded property GetFunction" src="http://UndocumentedMatlab.com/images/UDD_uitree_3.png" title="Overloaded property GetFunction" width="441" height="189" /><p
class="wp-caption-text">Overloaded property <b>GetFunction</b></p></div></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="http://UndocumentedMatlab.com/blog/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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Create a UDD tree-model instance</span>
&gt;&gt; uddTreeModel = com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">bean</span>.<span style="">UDDObjectTreeModel</span><span style="color: #080;">&#40;</span>a<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Get index of child e and its parent b:</span>
&gt;&gt; childIndex = uddTreeModel.<span style="">getIndexOfChild</span><span style="color: #080;">&#40;</span>b, e<span style="color: #080;">&#41;</span>
childIndex =
     <span style="color: #33f;">1</span>
&nbsp;
<span style="color: #228B22;">% Get the root's first child (#0):</span>
&gt;&gt; child0 = uddTreeModel.<span style="">getChild</span><span style="color: #080;">&#40;</span>a, <span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>
child0 =
  Name<span style="color: #F0F;">:</span> b
 Value<span style="color: #F0F;">:</span> <span style="color: #33f;">1.000000</span>
&nbsp;
<span style="color: #228B22;">% Get the path from node e to the root:</span>
&gt;&gt; path2root = uddTreeModel.<span style="">getPathToRoot</span><span style="color: #080;">&#40;</span>e<span style="color: #080;">&#41;</span>
path2root =
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">bean</span>.<span style="">UDDObject</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #F0F;">:</span>
    <span style="color: #080;">&#91;</span>simple_objectBeanAdapter2<span style="color: #080;">&#93;</span>      <span style="color: #228B22;">% &lt;= a</span>
    <span style="color: #080;">&#91;</span>simple_objectBeanAdapter2<span style="color: #080;">&#93;</span>      <span style="color: #228B22;">% &lt;= b</span>
    <span style="color: #080;">&#91;</span>simple_objectBeanAdapter2<span style="color: #080;">&#93;</span>      <span style="color: #228B22;">% &lt;= e</span>
&nbsp;
&gt;&gt; path2root<span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
  Name<span style="color: #F0F;">:</span> e
 Value<span style="color: #F0F;">:</span> <span style="color: #33f;">1.000000</span></pre></div></div><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><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/hierarchical-systems-with-udd/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Creating a simple UDD class</title><link>http://undocumentedmatlab.com/blog/creating-a-simple-udd-class/</link> <comments>http://undocumentedmatlab.com/blog/creating-a-simple-udd-class/#comments</comments> <pubDate>Wed, 23 Feb 2011 17:29:05 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[This article explains how to create and test custom UDD packages, classes and objects<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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><pre> </pre>]]></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.</p><p>To create this simple UDD class we need two directories and five m-files (downloadable <a
href="http://UndocumentedMatlab.com/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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%SCHEMA simple package definition function.</span>
   schema.<span style="">package</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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:</p><p>The first file is yet another schema.m file, which is the class-definition file:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%SCHEMA  simple.object class definition function.</span>
&nbsp;
   <span style="color: #228B22;">% Get a handle to the 'simple' package</span>
   simplePackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
&nbsp;
   <span style="color: #228B22;">% Create a base UDD object</span>
   simpleClass = schema.<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>simplePackage, <span style="color:#A020F0;">'object'</span><span style="color: #080;">&#41;</span>;
&nbsp;
   <span style="color: #228B22;">% Define the class methods:</span>
&nbsp;
   <span style="color: #228B22;">% dialog.m method</span>
   m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'dialog'</span><span style="color: #080;">&#41;</span>;
   s = m.<span style="">Signature</span>;
   s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
   s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
   s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>;
&nbsp;
   <span style="color: #228B22;">% disp.m method</span>
   m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'disp'</span><span style="color: #080;">&#41;</span>;
   s = m.<span style="">Signature</span>;
   s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
   s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
   s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>;
&nbsp;
   <span style="color: #228B22;">% Define the class properties:</span>
   schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'Name'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>;
   schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'Value'</span>, <span style="color:#A020F0;">'double'</span><span style="color: #080;">&#41;</span>;
&nbsp;
   <span style="color: #228B22;">% Define the class events:</span>
   schema.<span style="">event</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'simpleEvent'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> simpleObject = object<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%OBJECT constructor for the simple.object class</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   SIMPLEOBJECT = OBJECT(NAME, VALUE) creates an instance of the</span>
<span style="color: #228B22;">%   simple.object class with the Name property set to NAME and the</span>
<span style="color: #228B22;">%   Value property set VALUE</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   SIMPLEOBJECT = OBJECT(NAME) creates an instance of the simple.object</span>
<span style="color: #228B22;">%   class with the Name property set to NAME. The Value property will be</span>
<span style="color: #228B22;">%   given the default value of 0.</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   SIMPLEOBJECT = OBJECT creates an instance of the simple.object class</span>
<span style="color: #228B22;">%   and executes the simple.object dialog method to open a GUI for editing</span>
<span style="color: #228B22;">%   the Name and Value properties.</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   INPUTS:</span>
<span style="color: #228B22;">%       NAME          : string</span>
<span style="color: #228B22;">%       VALUE         : double</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   OUTPUTS:</span>
<span style="color: #228B22;">%       SIMPLEOBJECT  : simple.object instance</span>
   simpleObject = simple.<span style="">object</span>;
   <span style="color: #0000FF;">switch</span> <span style="color: #0000FF;">nargin</span>
      <span style="color: #0000FF;">case</span> <span style="color: #33f;">0</span>
         simpleObject.<span style="color: #0000FF;">dialog</span>;
      <span style="color: #0000FF;">case</span> <span style="color: #33f;">1</span>
         simpleObject.<span style="">Name</span> = name;
      <span style="color: #0000FF;">case</span> <span style="color: #33f;">2</span>
         simpleObject.<span style="">Name</span> = name;
         simpleObject.<span style="">Value</span> = value;
   <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>self<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%DISP overloaded object disp method</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   DISP(SELF) or SELF.DISP uses the MATLAB builtin DISP function</span>
<span style="color: #228B22;">%   to display the Name and Value properties of the object.</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   INPUTS:</span>
<span style="color: #228B22;">%       SELF  : simple.object instance</span>
   <span style="color: #0000FF;">builtin</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'disp'</span>, <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'  Name: %s\n Value: %f'</span>, self.<span style="">Name</span>, self.<span style="">Value</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #228B22;">%Alternative: fprintf('\n  Name: %s\n Value: %f', self.Name, self.Value));</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>And the dialog method (in dialog.m):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> <span style="color: #0000FF;">dialog</span><span style="color: #080;">&#40;</span>self<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%DIALOG dialog method for simple.object for use by openvar</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   DIALOG(SELF) or SELF.DIALOG where self is the name of the simple.object</span>
<span style="color: #228B22;">%   instance opens a gui to edit the Name and Value properties of self.</span>
<span style="color: #228B22;">%</span>
<span style="color: #228B22;">%   INPUTS:</span>
<span style="color: #228B22;">%       SELF  : simple.object</span>
   dlgValues = <span style="color: #0000FF;">inputdlg</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#123;</span><span style="color:#A020F0;">'Name:'</span>, <span style="color:#A020F0;">'Value:'</span><span style="color: #080;">&#125;</span>, <span style="color:#A020F0;">'simple.object'</span>, <span style="color: #33f;">1</span>, <span style="color: #080;">&#123;</span>self.<span style="">Name</span>, <span style="color: #0000FF;">mat2str</span><span style="color: #080;">&#40;</span>self.<span style="">Value</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">if</span> ~<span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>dlgValues<span style="color: #080;">&#41;</span>
      self.<span style="">Name</span> = dlgValues<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>;
      self.<span style="">Value</span> = <span style="color: #0000FF;">eval</span><span style="color: #080;">&#40;</span>dlgValues<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">a = simple.<span style="">object</span></pre></div></div><p>This calls the object&#8217;s constructor method, which launches the input dialog GUI:<br
/><center><div
class="wp-caption aligncenter" style="width: 191px"><img
alt="UDD simple class GUI" src="http://UndocumentedMatlab.com/images/UDD_simple_object_1.jpg" title="UDD simple class GUI" width="181" height="163" /><p
class="wp-caption-text">UDD simple class GUI</p></div></center></p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">a = 
  Name<span style="color: #F0F;">:</span> a
 Value<span style="color: #F0F;">:</span> <span style="color: #33f;">1.000000</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Alternatives for programmatically displaying the GUI</span>
a.<span style="color: #0000FF;">dialog</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% or simply: a.dialog</span>
<span style="color: #0000FF;">dialog</span><span style="color: #080;">&#40;</span>a<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">openvar</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'a'</span>,a<span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="text" style="font-family:monospace;">&gt; help simple.object
 OBJECT constructor for the simple.object class
&nbsp;
    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
&nbsp;
    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.
&nbsp;
    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.
&nbsp;
    INPUTS:
        NAME          : string
        VALUE         : double
&nbsp;
    OUTPUTS:
        SIMPLEOBJECT  : simple.object instance
&nbsp;
&gt;&gt; help simple.object.disp
 DISP overloaded object disp method
&nbsp;
    DISP(SELF) or SELF.DISP uses the MATLAB builtin DISP function
    to display the Name and Value properties of the object.
&nbsp;
    INPUTS:
        SELF  : simple.object instance</pre></div></div><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.</p><p>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!</p><p>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><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/creating-a-simple-udd-class/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>

<!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              b7666
Template:           category
-->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: undocumentedmatlab.com @ 2012-05-18 21:24:18 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/category/guest-bloggers/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      3.465s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1337401455; expires=Sun, 19-May-2013 04:24:15 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Sat, 19 May 2012 04:24:18 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Sat, 19 May 2012 05:24:18 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               ff3e12c342e6dd42b4e973beb252fe51
Content-Encoding:   gzip
-->
