<?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; Undocumented feature</title> <atom:link href="http://undocumentedmatlab.com/blog/tag/undocumented-feature/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>Preallocation performance</title><link>http://undocumentedmatlab.com/blog/preallocation-performance/</link> <comments>http://undocumentedmatlab.com/blog/preallocation-performance/#comments</comments> <pubDate>Wed, 16 May 2012 12:14:46 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[JIT]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2940</guid> <description><![CDATA[Preallocation is a standard Matlab speedup technique. Still, it has several undocumented aspects.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matrix-processing-performance/' rel='bookmark' title='Matrix processing performance'>Matrix processing performance</a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</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/datestr-performance/' rel='bookmark' title='datestr performance'>datestr performance</a> <small>Caching is a simple and very effective means to improve code performance, as demonstrated for the datestr function....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Array <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html#f8-793781">preallocation</a> is a standard and quite well-known technique for improving Matlab loop run-time performance. Today&#8217;s article will show that there is more than meets the eye for even such a simple coding technique.</p><p>A note of caution: in the examples that follow, don&#8217;t take any speedup as an expected actual value &#8211; the actual value may well be different on your system. Your mileage may vary. I only mean to display the relative differences between different alternatives.</p><h3 id="problem">The underlying problem</h3><p>Memory management has a direct influence on performance. I have already shown <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/">some examples of this</a> in past articles here.</p><p>Preallocation solves a basic problem in simple program loops, where an array is iteratively enlarged with new data (dynamic array growth). Unlike other programming languages (such as C, C++, C# or Java) that use static typing,  Matlab uses dynamic typing. This means that it is natural and easy to modify array size dynamically during program execution. For example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">fibonacci = <span style="color: #080;">&#91;</span><span style="color: #33f;">0</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>;
<span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">3</span> <span style="color: #F0F;">:</span> <span style="color: #33f;">100</span>
   fibonacci<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span> = fibonacci<span style="color: #080;">&#40;</span>idx-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> + fibonacci<span style="color: #080;">&#40;</span>idx-<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>While this may be simple to program, it is not wise with regards to performance. The reason is that whenever an array is resized (typically enlarged), Matlab allocates an entirely new contiguous block of memory for the array, copying the old values from the previous block to the new, then releasing the old block for potential reuse. This operation takes time to execute. In some cases, this reallocation might require accessing virtual memory and page swaps, which would take an even longer time to execute. If the operation is done in a loop, then performance could quickly drop off a cliff.</p><p>The cost of such naïve array growth is theoretically quadratic. This means that multiplying the number of elements by N multiplies the execution time by about N<sup>2</sup>. The reason for this is that Matlab needs to reallocate N times more than before, and each time takes N times longer due to the larger allocation size (the average block size multiplies by N), and N times more data elements to copy from the old to the new memory blocks.</p><p>A very interesting discussion of this phenomenon and various solutions can be found in a <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/102704">newsgroup thread from 2005</a>. Three main solutions were presented: preallocation, selective dynamic growth (<i>allocating headroom</i>) and using cell arrays. The best solution among these in terms of ease of use and performance is preallocation.</p><h3 id="basics">The basics of pre-allocation</h3><p>The basic idea of preallocation is to create a data array in the final expected size before actually starting the processing loop. This saves any reallocations within the loop, since all the data array elements are already available and can be accessed. This solution is useful when the final size is known in advance, as the following snippet illustrates:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Regular dynamic array growth:</span>
<span style="color: #0000FF;">tic</span>
fibonacci = <span style="color: #080;">&#91;</span><span style="color: #33f;">0</span>,<span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>;
<span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">3</span> <span style="color: #F0F;">:</span> <span style="color: #33f;">40000</span>
   fibonacci<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span> = fibonacci<span style="color: #080;">&#40;</span>idx-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> + fibonacci<span style="color: #080;">&#40;</span>idx-<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">toc</span>
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.019954</span> seconds.
&nbsp;
<span style="color: #228B22;">% Now use preallocation – 5 times faster than dynamic array growth:</span>
<span style="color: #0000FF;">tic</span>
fibonacci = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">40000</span>,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
fibonacci<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>=<span style="color: #33f;">0</span>; fibonacci<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>=<span style="color: #33f;">1</span>;
<span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">3</span> <span style="color: #F0F;">:</span> <span style="color: #33f;">40000</span>, 
   fibonacci<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span> = fibonacci<span style="color: #080;">&#40;</span>idx-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> + fibonacci<span style="color: #080;">&#40;</span>idx-<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">toc</span>
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.004132</span> seconds.</pre></div></div><p>On pre-R2011a releases the effect of preallocation is even more pronounced: I got a 35-times speedup on the same machine using Matlab 7.1 (R14 SP3). R2011a (Matlab 7.12) had a dramatic performance boost for such cases in the internal accelerator, so newer releases are much faster in dynamic allocations, but preallocation is still 5 times faster even on R2011a.</p><h3 id="nondeterministic">Non-deterministic pre-allocation</h3><p>Because the effect of preallocation is so dramatic on all Matlab releases, it makes sense to utilize it even in cases where the data array&#8217;s final size is not known in advance. We can do this by estimating an upper bound to the array&#8217;s size, preallocate this large size, and when we&#8217;re done remove any excess elements:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% The final array size is unknown – assume 1Kx3K upper bound (~23MB)</span>
data = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% estimated maximal size</span>
numRows = <span style="color: #33f;">0</span>;
numCols = <span style="color: #33f;">0</span>;
<span style="color: #0000FF;">while</span> <span style="color: #080;">&#40;</span>someCondition<span style="color: #080;">&#41;</span>
   colIdx = someValue1;   numCols = <span style="color: #0000FF;">max</span><span style="color: #080;">&#40;</span>numCols,colIdx<span style="color: #080;">&#41;</span>;
   rowIdx = someValue2;   numRows = <span style="color: #0000FF;">max</span><span style="color: #080;">&#40;</span>numRows,rowIdx<span style="color: #080;">&#41;</span>;
   data<span style="color: #080;">&#40;</span>rowIdx,colIdx<span style="color: #080;">&#41;</span> = someOtherValue;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% Now remove any excess elements</span>
data<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,numCols+<span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #0000FF;">end</span><span style="color: #080;">&#41;</span> = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>;   <span style="color: #228B22;">% remove excess columns</span>
data<span style="color: #080;">&#40;</span>numRows+<span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #0000FF;">end</span>,<span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span> = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>;   <span style="color: #228B22;">% remove excess rows</span></pre></div></div><h3 id="variants">Variants for pre-allocation</h3><p>It turns out that MathWorks&#8217; <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html#f8-793795">official suggestion</a> for preallocation, namely using the <i><b>zeros</b></i> function, is not the most efficient:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% MathWorks suggested variant</span>
<span style="color: #0000FF;">clear</span> data1, <span style="color: #0000FF;">tic</span>, data1 = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.016907</span> seconds.
&nbsp;
<span style="color: #228B22;">% A much faster alternative - 500 times faster!</span>
<span style="color: #0000FF;">clear</span> data1, <span style="color: #0000FF;">tic</span>, data1<span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000034</span> seconds.</pre></div></div><p>The reason for the second variant being so much faster is because it only allocates the memory, without worrying about the internal values (they get a default of 0, <i>false</i> or &#8221;, in case you wondered). On the other hand, <i><b>zeros</b></i> has to place a value in each of the allocated locations, which takes precious time.</p><p>In most cases the differences are immaterial since the preallocation code would only run once in the program, and an extra 17ms isn&#8217;t such a big deal. But in some cases we may have a need to periodically refresh our data, where the extra run-time could quickly accumulate.</p><h3 id="non-default">Pre-allocating non-default values</h3><p>When we need to preallocate a specific value into every data array element, we cannot use Variant #2. The reason is that Variant #2 only sets the very last data element, and all other array elements get assigned the default value (0, ‘’ or false, depending on the array’s data type). In this case, we can use one of the following alternatives (with their associated timings for a 1000&#215;3000 data array):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">scalar = <span style="color: #0000FF;">pi</span>;  <span style="color: #228B22;">% for example...</span>
&nbsp;
data = scalar<span style="color: #080;">&#40;</span><span style="color: #0000FF;">ones</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;           <span style="color: #228B22;">% Variant A: 87.680 msecs</span>
data<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span> = scalar;             <span style="color: #228B22;">% Variant B: 28.646 msecs</span>
data = <span style="color: #0000FF;">repmat</span><span style="color: #080;">&#40;</span>scalar,<span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span>;          <span style="color: #228B22;">% Variant C: 17.250 msecs</span>
data = scalar + <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span>;         <span style="color: #228B22;">% Variant D: 17.168 msecs</span>
data<span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; data = data+scalar;  <span style="color: #228B22;">% Variant E: 16.334 msecs</span></pre></div></div><p>As can be seen, Variants C-E are about twice as fast as Variant B, and 5 times faster than Variant A.</p><h3 id="non-double">Pre-allocating non-double data</h3><p>7.4.5 Preallocating non-double data<br
/> When preallocating an array of a type that is not <i><b>double</b></i>, we should be careful to create it using the desired type, to prevent memory and/or performance inefficiencies. For example, if we need to process a large array of small integers (<i><b>int8</b></i>), it would be inefficient to preallocate an array of doubles and type-convert to/from int8 within every loop iteration. Similarly, it would be inefficient to preallocate the array as a double type and then convert it to int8. Instead, we should create the array as an int8 array in the first place:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Bad idea: allocates 8MB double array, then converts to 1MB int8 array</span>
data = <span style="color: #0000FF;">int8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">1000</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;   <span style="color: #228B22;">% 1M elements</span>
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.008170</span> seconds.
&nbsp;
<span style="color: #228B22;">% Better: directly allocate the array as a 1MB int8 array – x80 faster</span>
data = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">1000</span>,<span style="color:#A020F0;">'int8'</span><span style="color: #080;">&#41;</span>;
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000095</span> seconds.</pre></div></div><h3 id="cells">Pre-allocating cell arrays</h3><p>To preallocate a cell-array we can use the cell function (explicit preallocation), or the maximal cell index (implicit preallocation). Explicit preallocation is faster than implicit preallocation, but functionally equivalent (Note: this is contrary to the experience with allocation of numeric arrays and other arrays):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Variant #1: Explicit preallocation of a 1Kx3K cell array</span>
data = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#41;</span>;
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.004637</span> seconds. 
&nbsp;
<span style="color: #228B22;">% Variant #2: Implicit preallocation – x3 slower than explicit</span>
<span style="color: #0000FF;">clear</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'data'</span><span style="color: #080;">&#41;</span>, data<span style="color: #080;">&#123;</span><span style="color: #33f;">1000</span>,<span style="color: #33f;">3000</span><span style="color: #080;">&#125;</span> = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>;
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.012873</span> seconds.</pre></div></div><h3 id="structs">Pre-allocating arrays of structs</h3><p>To preallocate an array of structs or class objects, we can use the <i><b>repmat</b></i> function to replicate copies of a single data element (explicit preallocation), or just use the maximal data index (implicit preallocation). In this case, unlike the case of cell arrays, implicit preallocation is much faster than explicit preallocation, since the single element does not actually need to be copied multiple times (<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-7S1YKO/">ref</a>):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Variant #1: Explicit preallocation of a 100x300 struct array</span>
element = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'field1'</span>,<span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'field2'</span>,<span style="color: #080;">&#123;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
data = <span style="color: #0000FF;">repmat</span><span style="color: #080;">&#40;</span>element, <span style="color: #33f;">100</span>, <span style="color: #33f;">300</span><span style="color: #080;">&#41;</span>;
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.002804</span> seconds. 
&nbsp;
<span style="color: #228B22;">% Variant #2: Implicit preallocation – x7 faster than explicit </span>
element = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'field1'</span>,<span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'field2'</span>,<span style="color: #080;">&#123;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">clear</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'data'</span><span style="color: #080;">&#41;</span>, data<span style="color: #080;">&#40;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">300</span><span style="color: #080;">&#41;</span> = element;
   =&gt; Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000429</span> seconds.</pre></div></div><p>When preallocating structs, we can also use a third variant, using the built-in struct feature of replicating the struct when the <i><b>struct</b></i> function is passed a cell array. For example, <code>struct('field1',cell(100,1), 'field2',5)</code> will create 100 structs, each of them having the empty field <i>field1</i> and another field called <i>field2</i> with value 5. Unfortunately, this variant is slower than both of the previous variants.</p><h3 id="objects">Pre-allocating class objects</h3><p>When preallocating in general, ensure that you are using the maximal expected array size. There is no point in preallocating an empty array or an array having a smaller size than the expected maximum, since dynamic memory reallocation will automatically kick-in within the processing-loop. For this reason, <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/2510427/how-to-preallocate-an-array-of-class-in-matlab">do not use</a> the <i>empty()</i> method of class objects to preallocate, but rather <i><b>repmat</b></i> as explained above.</p><p>When using <i><b>repmat</b></i> to replicate class objects, always be careful to note whether you are replicating the object itself (this happens if your class does NOT derive from <i><b>handle</b></i>) or its reference handle (which happens if you derive the class from <i><b>handle</b></i>). If you are replicating objects, then you can safely edit any of their properties independently of each other; but if you replicate references, you are merely using multiple copies of the same reference, so that modifying referenced object #1 will also automatically affect all the other referenced objects. This may or may not be suitable for your particular program requirements, so be careful to check carefully. If you actually need to use independent object copies, you will <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/591495/matlab-preallocate-a-non-numeric-vector#591788">need to call</a> the class constructor multiple times, once for each new independent object.</p><p
/><p>Next week: what if we can&#8217;t avoid dynamic array resizing? &#8211; apparently, all is not lost. Stay tuned&#8230;</p><p><i><br
/> Do you have any similar allocation-related tricks you&#8217;re using? or unexpected differences such as the ones shown above? If so, then please do <a
href="http://UndocumentedMatlab.com/blog/preallocation-performance/#respond">post a comment</a>.<br
/> </i></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matrix-processing-performance/' rel='bookmark' title='Matrix processing performance'>Matrix processing performance</a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</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/datestr-performance/' rel='bookmark' title='datestr performance'>datestr performance</a> <small>Caching is a simple and very effective means to improve code performance, as demonstrated for the datestr function....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/preallocation-performance/feed/</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Customizing menu items part 3</title><link>http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/</link> <comments>http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/#comments</comments> <pubDate>Wed, 09 May 2012 18:00:05 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Icons]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[JavaFrame]]></category> <category><![CDATA[Menubar]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2909</guid> <description><![CDATA[Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/' rel='bookmark' title='Customizing menu items part 2'>Customizing menu items part 2</a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>In the past weeks I&#8217;ve shown how Matlab menus can be customized in a variety of undocumented manners, using HTML, <a
target="_blank" href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/">pure Matlab</a>, and <a
target="_blank" href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/">Java</a>. Today I conclude this mini-series with an article that explains how to use the underlying Java object to customize menu item icons. Menu customizations are explored in depth in section 4.6 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">book</a>.</p><h3 id="underlying">A reminder: accessing the underlying Java object</h3><p>Matlab menus (<i><b>uimenu</b></i>) are basically simple wrappers for the much more powerful and flexible Java Swing <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html"><code>JMenu</code> and <code>JMenuItem</code></a> on which they are based.  Many important functionalities that are available in Java menus are missing from the Matlab <i><b>uimenu</b></i>s.</p><p>Getting the Java reference for the figure window&#8217;s main menu is very easy:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jFrame = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hFig<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'JavaFrame'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">try</span>
    <span style="color: #228B22;">% R2008a and later</span>
    jMenuBar = jFrame.<span style="">fHG1Client</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">catch</span>
    <span style="color: #228B22;">% R2007b and earlier</span>
    jMenuBar = jFrame.<span style="">fFigureClient</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>There are many customizations that can only be done using the Java handle: setting icons, several dozen callback types, tooltips, background color, font, text alignment, and so on. etc. Interested readers may wish to <i><b>get</b></i>/<i><b>set</b></i>/<i><b>inspect</b></i>/<i><b>methodsview</b></i>/<i><b><a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">uiinspect</a></b></i> the <code>jSave</code> reference handle and/or to read the documentation for <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JMenuItem.html"><code>JMenuItem</code></a>. Today&#8217;s article will focus on icon customizations.</p><h3 id="simple">Setting simple menu item icons</h3><p>Many of Matlab&#8217;s icons reside in either the <i>[matlabroot '/toolbox/matlab/icons/']</i> folder or the <i>[matlabroot '/java/jar/mwt.jar']</i> file (a JAR file is simply a zip file that includes Java classes and resources such as icon images). Let us create icons from the latter, to keep a consistent look-and-feel with the rest of Matlab (we could just as easily use our own external icon files):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% External icon file example</span>
jSave.<span style="">setIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'C:\Yair\save.gif'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% JAR resource example</span>
jarFile = <span style="color: #0000FF;">fullfile</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">matlabroot</span>,<span style="color:#A020F0;">'/java/jar/mwt.jar'</span><span style="color: #080;">&#41;</span>;
iconsFolder = <span style="color:#A020F0;">'/com/mathworks/mwt/resources/'</span>;
iconURI = <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'jar:file:/'</span> jarFile <span style="color:#A020F0;">'!'</span> iconsFolder <span style="color:#A020F0;">'save.gif'</span><span style="color: #080;">&#93;</span>;
iconURI = java.<span style="">net</span>.<span style="">URL</span><span style="color: #080;">&#40;</span>iconURI<span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% not necessary for external files</span>
jSave.<span style="">setIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span>iconURI<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Note that setting a menu item&#8217;s icon automatically re-aligns all other items in the menu, including those that do not have an icon (an internal bug that was introduced in R2010a causes a misalignment, as shown below):</p><p><center><div
class="wp-caption aligncenter" style="width: 240px"><img
alt="Menu item with a custom Icon (R2009b)" src="http://UndocumentedMatlab.com/images/uimenu3.png" title="Menu item with a custom Icon (R2009b)" width="230" height="120"/><p
class="wp-caption-text">Menu item with a custom <b>Icon</b> (R2009b)</p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 237px"><img
alt="...and the same in R2010a onward" src="http://UndocumentedMatlab.com/images/uimenu3b.png" title="...and the same in R2010a onward" width="227" height="120"/><p
class="wp-caption-text">...and the same in R2010a onward</p></div></center></p><h3 id="checkmark">Checkmark icon</h3><p>The empty space on the left of the menu is reserved for the check mark. Each Matlab menu item is check-able, since it is an object that extends the <code>com.mathworks.mwswing.MJCheckBoxMenuItem</code> class. I have not found a way to eliminate this empty space, which is really unnecessary in the File-menu case (it is only actually necessary in the View and Tools menus). Note that if an icon is set for the item, both the icon and the checkmark will be displayed, side by side.</p><p>The check mark is controlled by the <b>State</b> property of the Java object (which accepts logical true/false values), or the <b>Checked</b> property of the Matlab handle (which accepts the regular &#8216;on&#8217;/'off&#8217; string values):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Set the check mark at the Matlab level</span>
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>findall<span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'figMenuFileSave'</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'Checked'</span>,<span style="color:#A020F0;">'on'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Equivalent - set the checkmark at the Java level</span>
jSave.<span style="">setState</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 195px"><img
alt="State = true, Icon = [ ]" src="http://UndocumentedMatlab.com/images/uimenu_save_checked1.png" title="State = true, Icon = [ ]" width="185" height="138"/><p
class="wp-caption-text"><b>State</b> = true, <b>Icon</b> = &#91; &#93;</p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 215px"><img
alt="State = true, Icon = custom" src="http://UndocumentedMatlab.com/images/uimenu_save_checked2.png" title="State = true, Icon = custom" width="205" height="137"/><p
class="wp-caption-text"><b>State</b> = true, <b>Icon</b> = custom</p></div></center></p><h3 id="custom">Customizing menu icons</h3><p>Icons can be customized: modify the gap between the icon and the label with the <b>IconTextGap</b> property (default = 4 [pixels]); place icons to the right of the label by setting <b>HorizontalTextPosition</b> to <code>jSave.LEFT</code> (=2), or centered using <code>jSave.CENTER</code> (=0). Note that the above-mentioned misalignment bug does not appear in these cases:</p><p><center><div
class="wp-caption aligncenter" style="width: 232px"><img
alt="jSave.setHorizontalTextPosition(jSave.LEFT)" src="http://UndocumentedMatlab.com/images/uimenu4.png" title="jSave.setHorizontalTextPosition(jSave.LEFT)" width="222" height="121"/><p
class="wp-caption-text"><code>jSave.setHorizontalTextPosition<br
/>(jSave.LEFT)</code></p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 233px"><img
alt="jSave.setHorizontalTextPosition(jSave.CENTER)" src="http://UndocumentedMatlab.com/images/uimenu5.png" title="jSave.setHorizontalTextPosition(jSave.CENTER)" width="223" height="120"/><p
class="wp-caption-text"><code>jSave.setHorizontalTextPosition<br
/>(jSave.CENTER)</code></p></div></center></p><p>Note how the label text can be seen through (or on top of) the icon when it is centered. This feature can be used to create stunning menu effects as shown below. Note how the width and height of the menu item automatically increased to accommodate my new 77&#215;31 icon size (icons are normally sized 16&#215;16 pixels):</p><p><center><div
class="wp-caption aligncenter" style="width: 295px"><img
alt="Overlaid icon (HorizontalTextPosition = CENTER)" src="http://UndocumentedMatlab.com/images/uimenu6.png" title="Overlaid icon (HorizontalTextPosition = CENTER)" width="285" height="136"/><p
class="wp-caption-text">Overlaid icon (<b>HorizontalTextPosition</b> = CENTER)</p></div></center></p><p>To resize an icon programmatically before setting it in a Java component, we can use the following example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">myIcon = <span style="color: #0000FF;">fullfile</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">matlabroot</span>,<span style="color:#A020F0;">'/toolbox/matlab/icons/matlabicon.gif'</span><span style="color: #080;">&#41;</span>;
imageToolkit = java.<span style="">awt</span>.<span style="">Toolkit</span>.<span style="">getDefaultToolkit</span>;
iconImage = imageToolkit.<span style="">createImage</span><span style="color: #080;">&#40;</span>myIcon<span style="color: #080;">&#41;</span>;
iconImage = iconImage.<span style="">getScaledInstance</span><span style="color: #080;">&#40;</span><span style="color: #33f;">32</span>,<span style="color: #33f;">32</span>,iconImage.<span style="">SCALE_SMOOTH</span><span style="color: #080;">&#41;</span>;
jSave.<span style="">setIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span>iconImage<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Remember when rescaling images, particularly small ones with few pixels, that it is always better to shrink than to enlarge images: enlarging a small icon image might introduce a significant pixelization effect:</p><p><center><div
class="wp-caption aligncenter" style="width: 100px"><img
alt="16x16 icon image resized to 32x32" src="http://UndocumentedMatlab.com/images/button_icon2.png" title="16x16 icon image resized to 32x32" width="90" height="90"/><p
class="wp-caption-text">16x16 icon image resized to 32x32</p></div></center></p><p>Separate icons can be specified for a different appearance during mouse hover (<b>RolloverIcon</b>; requires <b>RolloverEnabled</b>=1), item click/press (<b>PressedIcon</b>), item selection (<b>SelectedIcon</b>, <b>RolloverSelectedIcon</b>, <b>DisabledSelectedIcon</b>), and disabled menu item (<b>DisabledIcon</b>). All these properties are empty ([]) by default, which applies a predefined default variation (image color filter) to the main item&#8217;s Icon. For example, let us modify <b>DisabledIcon</b>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">myIcon = <span style="color:#A020F0;">'C:\Yair\Undocumented Matlab\Images\save_disabled.gif'</span>;
jSaveAs.<span style="">setDisabledIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span>myIcon<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
jSaveAs.<span style="">setEnabled</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">false</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 130px"><img
alt="Enabled, main Icon" src="http://UndocumentedMatlab.com/images/uimenu7a.png" title="Enabled, main Icon" width="120" height="135"/><p
class="wp-caption-text">Enabled, main <b>Icon</b></p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 170px"><img
alt="Disabled, default Icon variation" src="http://UndocumentedMatlab.com/images/uimenu7b.png" title="Disabled, default Icon variation" width="120" height="135"/><p
class="wp-caption-text">Disabled, default <b>Icon</b> variation</p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 180px"><img
alt="Disabled, custom DisabledIcon" src="http://UndocumentedMatlab.com/images/uimenu7c.png" title="Disabled, custom DisabledIcon" width="120" height="135"/><p
class="wp-caption-text">Disabled, custom <b>DisabledIcon</b></p></div></center></p><p>Note the automatic graying of disabled menu items, including their icon. This effect can also be achieved programmatically using the static methods in <code>com.mathworks.mwswing.IconUtils</code>: <i>changeIconColor(), createBadgedIcon(), createGhostedIcon()</i>, and <i>createSelectedIcon()</i>. When we use a non-default custom <b>DisabledIcon</b>, it is used instead of the gray icon variant.</p><p>This concludes my mini-series of customizing menus in Matlab. If you have used any nifty customization that I have not mentioned, please post a comment about it <a
href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/#respond">below</a>.</p><p><span
class="alignleft"><img
alt="Ken &#038; Mike" src="http://UndocumentedMatlab.com/images/ken_and_mike.png" title="Ken &#038; Mike" width="98" height="83"/></span>In an unrelated note, I would like to extend good wishes to Mike Katz, who has left the MathWorks mobile development team to join Kinvey a few days ago. Mike has been with MathWorks since 2005 and has been responsible for maintaining the official <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/">MATLAB Desktop blog</a>, together with <a
target="_blank" href="http://undocumentedmatlab.com/blog/gui-integrated-browser-control/">Ken Orr</a>. I&#8217;m not sure yet which direction the Desktop blog will take, and by whom, but in any case it won&#8217;t be the same. You&#8217;re both missed, Mike &#038; Ken!</p><p
/>&nbsp;</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/' rel='bookmark' title='Customizing menu items part 2'>Customizing menu items part 2</a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Customizing menu items part 2</title><link>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/</link> <comments>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/#comments</comments> <pubDate>Wed, 02 May 2012 11:57:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[JavaFrame]]></category> <category><![CDATA[Menubar]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2902</guid> <description><![CDATA[Matlab menu items can be customized in a variety of useful ways using their underlying Java object.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/' rel='bookmark' title='Customizing menu items part 3'>Customizing menu items part 3</a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-workspace-context-menu/' rel='bookmark' title='Customizing Workspace context-menu'>Customizing Workspace context-menu</a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Last week I <a
target="_blank" href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/">explained</a> how to customize Matlab&#8217;s menu items using some undocumented tricks that do not need Java. Today I will show how using just a tiny bit of Java magic powder we can add much more complex customizations to menu items. Menu customizations are explored in depth in section 4.6 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">book</a>.</p><h3 id="underlying">Accessing the underlying Java object</h3><p>Matlab menus (<i><b>uimenu</b></i>) are basically simple wrappers for the much more powerful and flexible Java Swing <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html"><code>JMenu</code> and <code>JMenuItem</code></a> on which they are based.  Many important functionalities that are available in Java menus are missing from the Matlab <i><b>uimenu</b></i>s.</p><p>Getting the Java reference for the figure window&#8217;s main menu is very easy:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jFrame = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hFig<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'JavaFrame'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">try</span>
    <span style="color: #228B22;">% R2008a and later</span>
    jMenuBar = jFrame.<span style="">fHG1Client</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">catch</span>
    <span style="color: #228B22;">% R2007b and earlier</span>
    jMenuBar = jFrame.<span style="">fFigureClient</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Note that we have used the figure handle&#8217;s hidden <a
target="_blank" href="http://undocumentedmatlab.com/blog/minimize-maximize-figure-window/#JavaFrame"><b>JavaFrame</b> property</a>, accessed through the reference&#8217;s <i><b>handle</b></i>() wrapper, to prevent an annoying warning message.</p><p>There are many customizations that can only be done using the Java handle: setting icons, several dozen callback types, tooltips, background color, font, text alignment, and so on. etc. Interested readers may wish to <i><b>get</b></i>/<i><b>set</b></i>/<i><b>inspect</b></i>/<i><b>methodsview</b></i>/<i><b><a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">uiinspect</a></b></i> the <code>jSave</code> reference handle and/or to read the documentation for <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JMenuItem.html"><code>JMenuItem</code></a>. Some useful examples are provided below.</p><h3 id="dynamic">Dynamic menu behavior</h3><p>As a first example of Java-based customization, let us add DHTML-like behavior to the menu, such that the menu items will automatically be displayed when the mouse hovers over the item, without waiting for a user mouse click. First, get the <code>jMenuBar</code> reference as described above. Now, set the <b>MouseEnteredCallback</b> to automatically simulate a user mouse click on each menu item using its <i>doClick()</i> method. Setting the callback should be done separately to each of the top-level menu components:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">for</span> menuIdx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> jMenuBar.<span style="">getComponentCount</span>
    jMenu = jMenuBar.<span style="">getComponent</span><span style="color: #080;">&#40;</span>menuIdx-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
    hjMenu = handle<span style="color: #080;">&#40;</span>jMenu,<span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hjMenu,<span style="color:#A020F0;">'MouseEnteredCallback'</span>,<span style="color:#A020F0;">'doClick(gcbo)'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Note that using this mechanism may be awkward if the top-level menu does not have a sub-menu but is rather a stand-alone menu item. For example, if the top-level menu-item &#8220;Help&#8221; is a stand-alone menu button (i.e., there are no help menu-items, just the single Help item), then moving the mouse over this item will trigger the help event, although the user did not actually click on the item. To prevent this behavior, we should modify the code snippet above to only work on those menu items that have sub-items.</p><h3 id="accelerator">Custom accelerator shortcut keys</h3><p>As another example, Matlab automatically assigns a non-modifiable keyboard accelerator key modifier of <ctrl>, while JMenus allow any combination of Alt/Ctrl/Shift/Meta (depending on the platform). Let us modify the default File/Save accelerator key from &#8216;Ctrl-S&#8217; to &#8216;Alt-Shift-S&#8217; as an example. We need a reference for the &#8220;Save&#8221; menu item. Note that unlike regular Java components, menu items are retrieved using the <i>getMenuComponent()</i> method and not <i>getComponent()</i>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% File main menu is the first main menu item =&gt; index=0</span>
jFileMenu = jMenuBar.<span style="">getComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Save menu item is the 5th menu item (separators included)</span>
jSave = jFileMenu.<span style="">getMenuComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>; <span style="color: #228B22;">%Java indexes start with 0!</span>
inspect<span style="color: #080;">&#40;</span>jSave<span style="color: #080;">&#41;</span> 	<span style="color: #228B22;">% just to be sure: label='Save' =&gt; good!</span>
&nbsp;
<span style="color: #228B22;">% Finally, set a new accelerator key for this menu item:</span>
jAccelerator = javax.<span style="">swing</span>.<span style="">KeyStroke</span>.<span style="">getKeyStroke</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'alt shift S'</span><span style="color: #080;">&#41;</span>;
jSave.<span style="">setAccelerator</span><span style="color: #080;">&#40;</span>jAccelerator<span style="color: #080;">&#41;</span>;</pre></div></div><p>That is all there is to it – the label is modified automatically to reflect the new keyboard accelerator key. More info on setting different combinations of accelerator keys and modifiers can be found in the official Java documentation for <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/KeyStroke.html#getKeyStroke%28java.lang.String%29"><code>KeyStroke</code></a>.</p><p><center><div
class="wp-caption aligncenter" style="width: 212px"><img
alt="Modification of menu item accelerator and tooltip" src="http://UndocumentedMatlab.com/images/uimenu1.png" title="Modification of menu item accelerator and tooltip" width="202" height="200"/><p
class="wp-caption-text">Modification of menu item accelerator and tooltip</p></div></center></p><p>Note that the Save menu-item reference can only be retrieved after opening the File menu at least once earlier; otherwise, an exception will be thrown when trying to access the menu item. The File menu does NOT need to remain open – it only needs to have been opened sometime earlier, for its menu items to be rendered. This can be done either interactively (by selecting the File menu) or programmatically:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Simulate mouse clicks to force the File main-menu to open &amp; close</span>
jFileMenu.<span style="">doClick</span>; <span style="color: #228B22;">% open the File menu</span>
jFileMenu.<span style="">doClick</span>; <span style="color: #228B22;">% close the menu</span>
&nbsp;
<span style="color: #228B22;">% Now the Save menu is accessible:</span>
jSave = jFileMenu.<span style="">getMenuComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>;</pre></div></div><h3 id="tooltip">Tooltip and highlight</h3><p>For some unknown reason, MathWorks did not include a tooltip property in its Matlab menu handle, contrary to all the other Matlab GUI components. So we must use the Java handle, specifically the <b>ToolTipText</b> property:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jSave.<span style="">setToolTipText</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'modified menu item with tooltip'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Java menu items also contain a property called <b>Armed</b>, which is a logical value (default=false). When turned on, the menu item is highlighted just as when it is selected (see the <i>Save As&#8230;</i> menu item in the screenshot above). On a Windows system, this means a blue background:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jSave.<span style="">setArmed</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>When the item is actually selected and then de-selected, <b>Armed</b> reverts to a false (off) value. Alternating the <b>Armed</b> property value can achieve an effect of flashing the menu item.</p><h3 id="callbacks">Callbacks</h3><p>In addition to the standard Swing control callbacks discussed in an <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/">earlier article</a>, menu items possess several additional callbacks that are specific to menu items, including:</p><ul><li><b>ActionPerformedCallback</b> – fired when the menu item is invoked</li><li><b>StateChangedCallback</b> – fired when the menu item is selected or deselected</li><li><b>MenuDragMouseXXXCallback</b> (XXX=Dragged/Entered/Exited/Released) – fired when the menu item is dragged, for the corresponding event</li><li><b>MenuKeyXXXCallback</b> (XXX=Pressed/Released/Typed) – fired when a keyboard click event occurs (the menu item&#8217;s accelerator was typed)</li></ul><p>Using these callbacks, together with the 30-odd standard Swing callbacks, we can control our menu&#8217;s behavior to a much higher degree than possible using the standard Matlab handle.</p><p>Next week, I will conclude this mini-series with an article explaining how to customize menu item icons.</ctrl></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/' rel='bookmark' title='Customizing menu items part 3'>Customizing menu items part 3</a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-workspace-context-menu/' rel='bookmark' title='Customizing Workspace context-menu'>Customizing Workspace context-menu</a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Spy Easter egg take 2</title><link>http://undocumentedmatlab.com/blog/spy-easter-egg-take-2/</link> <comments>http://undocumentedmatlab.com/blog/spy-easter-egg-take-2/#comments</comments> <pubDate>Wed, 04 Apr 2012 18:00:12 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Easter egg]]></category> <category><![CDATA[Pure Matlab]]></category> <category><![CDATA[spy]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2833</guid> <description><![CDATA[The default spy Easter-egg image in the spy function has recently changed.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/spy-easter-egg/' rel='bookmark' title='Spy Easter egg'>Spy Easter egg</a> <small>The built-in Matlab function spy has an undocumented feature (Easter egg) when it is called with no input arguments....</small></li><li><a
href='http://undocumentedmatlab.com/blog/image-easter-egg/' rel='bookmark' title='Image Easter egg'>Image Easter egg</a> <small>The default image presented by Matlab's image function has a very interesting undocumented story....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matrix-processing-performance/' rel='bookmark' title='Matrix processing performance'>Matrix processing performance</a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li><li><a
href='http://undocumentedmatlab.com/blog/modifying-default-toolbar-menubar-actions/' rel='bookmark' title='Modifying default toolbar/menubar actions'>Modifying default toolbar/menubar actions</a> <small>The default Matlab figure toolbar and menu actions can easily be modified using simple pure-Matlab code. This article explains how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Three years ago, I posted a <a
target="_blank" href="http://undocumentedmatlab.com/blog/spy-easter-egg/">short post</a> about Matlab&#8217;s built-in Easter egg in the <i><b>spy</b></i> function. Apparently, when running <i><b>spy</b></i> with no input arguments, it uses an undocumented default built-in sparse matrix that generates the white spy in the famous <a
href="http://en.wikipedia.org/wiki/Spy_vs._Spy" target="_blank" rel="nofollow">Spy vs. Spy</a> comics series:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; spy;</pre></div></div><p><center><img
src="http://undocumentedmatlab.com/images/spy.png" title="Matlab spy Easter egg" alt="Matlab spy Easter egg" width="327" height="388"/></center></p><p>As was recently <a
target="_blank" rel="nofollow" href="http://blog.developpez.com/matlab4geek/p10681/pensee-matlab-du-jour/notre-vieil-espion-qui-a-pris-sa-retrait/?page=2">reported</a> by Aurélien, the default built-in sparse matrix has changed in R2011a (not R2011b as in the original report):</p><p><center><img
src="http://undocumentedmatlab.com/images/spy2.png" title="Matlab spy Easter egg" alt="Matlab spy Easter egg" width="262" height="391"/></center></p><p>If you ask me, the previous (white spy) image had more relevance to the <i><b>spy</b></i> function&#8230; I assume the new image was not chosen arbitrarily &#8211; if anyone has some insight as to why this image was chosen and its relevance to <i><b>spy</b></i>, please post a comment.</p><p><b><u>Addendum</u></b>: The original spy image can still be generated using the following code snippet:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">c = <span style="color: #080;">&#91;</span><span style="color:#A020F0;">';@3EA4:aei7]ced.CFHE;4\T&gt;*Y&gt;,dL0,HOQQMJLJE9PX[[Q.ZF.\JTCA1dd'</span>
     <span style="color:#A020F0;">'&lt;a ;FB:;bfj8^df//DGIF&amp;lt;5]UF+ZH-eM&gt;-IorRPNMPIE-Y\\R8[I8]SUDW2e+'</span>
     <span style="color:#A020F0;">'=4BGC;&lt;cgk9_e00deojg =6^VG,[I.fN?5jpsSQPNQPF.Z,]S9`S9cTWVX:+,'</span>
     <span style="color:#A020F0;">':5CHD&lt;=4hlh`f11EFPKHA7&amp;WH-\J/gOC?kqtTRRORQJ8--^TB+T=dWYWY;,_'</span>
     <span style="color:#A020F0;">';6D3E=&gt;7imiag2IFOQLID8'</span><span style="color:#A020F0;">'XI.]K0&quot;PD@l32UZhP//P988_WC,U&gt;+Z^Y\&amp;lt;2`'</span>
     <span style="color:#A020F0;">'&amp;lt;82BF&gt;?8jnjbhLJGPRMJE9/YJ/`L1#QMC$;;V[iv09QE99,XD.YB,[_\]=3a'</span>
     <span style="color:#A020F0;">'&gt;9;CG?@9kokc2MKHQSOKF:0ZL0aM2$RNG%AAW\jw9E.FEE-_G8aG.d`]_W5+'</span>
     <span style="color:#A020F0;">'?:CDH@A:lpld3NLIRTPLG=1[M1bN3%SOH4BBX]kx:J9LLL8`H9bJ/+d_dX6,'</span>
     <span style="color:#A020F0;">'@;DEIAB;mqmePOMJSUQMJ&gt;2\N2cO4&amp;TPP@HCY^lyDKEMMN9+I@+S8,+deY7^'</span>
     <span style="color:#A020F0;">'8@EFJBC&amp;lt;4rnfQPNPTVRNKB3]O3dP5'</span><span style="color:#A020F0;">'UQQCIDZ_mzEPFNNOE,RA,T9/,++\8_'</span>
     <span style="color:#A020F0;">'9A2G3CD=544gRQPQUWUOLE4^P4&quot;Q6(VRRIJE[`n{KQKOOPK-SE.W:F/,,]Z+'</span>
     <span style="color:#A020F0;">':BDH4DE&gt;655hSRQRVXVPMF5_Q5#R&gt;)eSSJKF\ao0L.L-WUL.VF8XCH001_[,'</span>
     <span style="color:#A020F0;">';3EI&lt;eo ?766iTSRSWYWQNG6$R6'</span><span style="color:#A020F0;">'S?*fTTlLQ]bp1M/P.XVP8[H9]DIDA=`\]'</span>
     <span style="color:#A020F0;">'?4D3=FP@877jUTSTXZXROK7%S7(TF+gUUmMR^cq:N9Q8YZQ9_I&gt;cIJEB&gt;d_^'</span>
     <span style="color:#A020F0;">'@5E@&gt;GQA98b3VUTUY*YSPL8&amp;T&gt;)UI,hVhnNS_dr;PE.9Z[RCaR?+JTFC?e`+'</span>
     <span style="color:#A020F0;">'79FA?HRB:9c4WVUVZ+ZWQM=,WG*VJ-&quot;gi4OT`es&lt;ql9e [\TD+SA,SWUVW+d,'</span>
     <span style="color:#A020F0;">'8:3B@JSX;:dVXWVW[,[XRN&gt;-XH+bK.#hj@PUvftDRMEF,]UH,UB.TYVWX,e\'</span>
     <span style="color:#A020F0;">'9;ECAKTY&lt; ;eWYXWX\:)YSOE.YI,cL/$ikCqV1guE/PFL-^XI-YG/WZWXY1+]'</span>
     <span style="color:#A020F0;">':AFDBLUZ=&lt;fXZYXY,;*ZTPF/ZJ-dM0%j#Jrt2hxH0QKM8,YJ.ZI8[^YY\2,,'</span>
     <span style="color:#A020F0;">';B3ECMV[&gt;jgY[ZYZ-&amp;lt;7[XQG0[K.eN1&amp;&quot;$K2u:iyO9.PN9-_K8aJ9\_]\]82['</span>
     <span style="color:#A020F0;">'?CEFDNW\?khZ\[Z[==8\YRH1\M/!O2'</span><span style="color:#A020F0;">'#%m31Bw0PE/QXE8+R9bS;da^]_93\'</span>
     <span style="color:#A020F0;">'@2FGEOX]ali[]\[\&gt;&gt;9(ZSL2]N0&quot;P3($&amp;n;2Cx1QN9--L9,SA+T&lt; +d__`:4,'</span>
     <span style="color:#A020F0;">'A3GHFPY^bmj\^]\]??:)[TM3^O1%Q4)%'</span><span style="color:#A020F0;">'oA:D0:0OE.8ME-TE,XB,+`da;5['</span>
     <span style="color:#A020F0;">'643IGQZ_cnk]_^]^@@;5\UN4_P2&amp;R6*&amp;(3B;E1&amp;lt;1PN99NL8WF.^C/,a+bY6,'</span>
     <span style="color:#A020F0;">'7:F3HR[`dol^`_^_AA&amp;lt;6]VO5`Q3'</span><span style="color:#A020F0;">'S&gt;+'</span><span style="color:#A020F0;">');CBF:=:QOEEOO9_G8aH6/d,cZ[Y'</span>
     <span style="color:#A020F0;">'8;G4IS\aep4_a`_-BD=7'</span><span style="color:#A020F0;">'XP6aR4(T?,(5@DCHCC;RPFLPPD`H9bJ70+0d\\Z'</span>
     <span style="color:#A020F0;">'9BH&gt;JT^bf45`ba`.CE@8(YQ7#S5)UD-)?AEDIDDD/QKMVQJ+S?cSDF,1e]a,'</span>
     <span style="color:#A020F0;">':C3?K4_cg5[acbaADFA92ZR8$T6*VE.*@JFEJEEE0.NNWTK,U@+TEG0?+_bX'</span>
     <span style="color:#A020F0;">';2D@L9`dh6\bdcbBEGD:3[S=)U7+cK/+CKGFLIKI9/OWZUL-VA,WIHB@,`cY'</span><span style="color: #080;">&#93;</span>;
<span style="color: #0000FF;"><span style="color: #33f;">i</span></span> = <span style="color: #0000FF;">double</span><span style="color: #080;">&#40;</span>c<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span>-<span style="color: #33f;">32</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;"><span style="color: #33f;">j</span></span> = <span style="color: #0000FF;">cumsum</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">diff</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span><span style="color: #33f;">0</span>; <span style="color: #0000FF;"><span style="color: #33f;">i</span></span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>&lt; =<span style="color: #33f;">0</span><span style="color: #080;">&#41;</span> + <span style="color: #33f;">1</span>;
S = <span style="color: #0000FF;">sparse</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;"><span style="color: #33f;">i</span></span>,<span style="color: #0000FF;"><span style="color: #33f;">j</span></span>,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>';
spy<span style="color: #080;">&#40;</span>S<span style="color: #080;">&#41;</span></pre></div></div><p>Happy Easter / Passover everybody!</p><p></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/spy-easter-egg/' rel='bookmark' title='Spy Easter egg'>Spy Easter egg</a> <small>The built-in Matlab function spy has an undocumented feature (Easter egg) when it is called with no input arguments....</small></li><li><a
href='http://undocumentedmatlab.com/blog/image-easter-egg/' rel='bookmark' title='Image Easter egg'>Image Easter egg</a> <small>The default image presented by Matlab's image function has a very interesting undocumented story....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matrix-processing-performance/' rel='bookmark' title='Matrix processing performance'>Matrix processing performance</a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li><li><a
href='http://undocumentedmatlab.com/blog/modifying-default-toolbar-menubar-actions/' rel='bookmark' title='Modifying default toolbar/menubar actions'>Modifying default toolbar/menubar actions</a> <small>The default Matlab figure toolbar and menu actions can easily be modified using simple pure-Matlab code. This article explains how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/spy-easter-egg-take-2/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <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>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>Recovering previous editor state</title><link>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/</link> <comments>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/#comments</comments> <pubDate>Wed, 11 Jan 2012 18:00:49 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Desktop]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Editor]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2656</guid> <description><![CDATA[Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/non-textual-editor-actions/' rel='bookmark' title='Non-textual editor actions'>Non-textual editor actions</a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-assign-a-keyboard-macro-in-the-matlab-editor/' rel='bookmark' title='EditorMacro &#8211; assign a keyboard macro in the Matlab editor'>EditorMacro &#8211; assign a keyboard macro in the Matlab editor</a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/tri-state-checkbox/' rel='bookmark' title='Tri-state checkbox'>Tri-state checkbox</a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><span
class="alignright"><img
title="Editor with multiple loaded documents" src="http://undocumentedmatlab.com/images/editor.png" alt="Editor with multiple loaded documents" width="300" height="380"/></span> I find it very useful to use the Matlab editor&#8217;s ability to load multiple files to help me remember which files I still need to work on. I typically have a few dozen files loaded in the editor. I guess you could say that the editor&#8217;s list of files is a simple reflection of my open tasks. It would be extremely inconvenient if I ever lost this list.</p><p>Which is, unfortunately, exactly what happened to me yesterday.</p><p>I was about to close a figure window and accidentally closed the editor window that was behind it.</p><p>I was now in quite a jam: reopening the editor would not load all my files, but start with a blank (empty) editor. The Matlab editor, unlike modern browsers, does not have a &#8216;reopen last session&#8217; option, and using the most-recently-used (MRU) files list would at best return the latest 9 files (the default Matlab preference is to have an MRU depth of only 4 files, but this is one of the very first things that I change whenever I install Matlab, along with a few other very questionable [IMHO] default preferences).</p><p>Luckily for me, there is an escape hatch: Matlab stores its Desktop windows state in a file called <i>MATLABDesktop.xml</i> that is located in the user&#8217;s <i><b>prefdir</b></i> folder. This file includes information about the position and state (docked/undocked etc.) of every Desktop window. Since the editor files are considered Desktop documents (you can see them under the Desktop&#8217;s main menu&#8217;s Window menu), they are also included in this file. When I closed the Editor, these documents were simply removed from the <i>MATLABDesktop.xml</i> file.</p><p>It turns out that Matlab automatically stores a backup version of this file in another file called <i>MATLABDesktop.xml.prev</i>, in the same <i><b>prefdir</b></i> folder. We can inspect the folder using our system&#8217;s file browser. For example, on Windows we could use:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">winopen<span style="color: #080;">&#40;</span>prefdir<span style="color: #080;">&#41;</span></pre></div></div><p>So before doing anything else, I closed Matlab (I actually crashed it to prevent any cleanup tasks to accidentally erase this backup file, but that turned out to be an unnecessary precaution), deleted the latest <i>MATLABDesktop.xml</i> file, replaced it with a copy of the <i>MATLABDesktop.xml.prev</i> file (which I renamed <i>MATLABDesktop.xml</i>), and only then did I restart Matlab.</p><p>Problem solved &#8211; everything back to normal. Resume breathing. Once again I have my never-ending virtual task list in front of me as I write this.</p><p>Lessons learned:</p><ol><li>don&#8217;t be too quick on the close button trigger</li><li>always keep a relatively recent backup copy of your important config files (BTW, I use the same advice with my FireFox browser, where I normally have dozens of open tabs &#8211; I keep a backup copy of the sessionstore.js file)</li><li>if you do get into a jam, don&#8217;t do anything hasty that might make recovery impossible. Calm down, look around, and maybe you&#8217;ll find an automatic backup somewhere</li></ol><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/non-textual-editor-actions/' rel='bookmark' title='Non-textual editor actions'>Non-textual editor actions</a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-assign-a-keyboard-macro-in-the-matlab-editor/' rel='bookmark' title='EditorMacro &#8211; assign a keyboard macro in the Matlab editor'>EditorMacro &#8211; assign a keyboard macro in the Matlab editor</a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/tri-state-checkbox/' rel='bookmark' title='Tri-state checkbox'>Tri-state checkbox</a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Types of undocumented Matlab aspects</title><link>http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/</link> <comments>http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/#comments</comments> <pubDate>Thu, 24 Nov 2011 18:00:36 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented feature]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Undocumented function]]></category> <category><![CDATA[Hidden property]]></category> <category><![CDATA[Internal component]]></category> <category><![CDATA[JMI]]></category> <category><![CDATA[Pure Matlab]]></category> <category><![CDATA[Undocumented property]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2534</guid> <description><![CDATA[This article lists the different types of undocumented/unsupported/hidden aspects in Matlab<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/reasons-for-undocumented-matlab-aspects/' rel='bookmark' title='Reasons for undocumented Matlab aspects'>Reasons for undocumented Matlab aspects</a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-cursorbar-object/' rel='bookmark' title='Undocumented cursorbar object'>Undocumented cursorbar object</a> <small>Matlab's internal undocumented graphics.cursorbar object can be used to present dynamic data-tip cross-hairs...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uiundo-matlab-undocumented-undo-redo-manager/' rel='bookmark' title='uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager'>uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager</a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li><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></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Why are there so many undocumented aspects in Matlab?</p><p>This is a great question, recently <a
target="_blank" href="http://undocumentedmatlab.com/blog/guide-customization/#comment-61578">asked</a> by a reader of this blog, so I wanted to expand on it in next week&#8217;s article. Before specifying the different reasons, let&#8217;s map the nature of undocumented aspects that we find in Matlab.</p><p>The term <i>undocumented/unsupported</i> (as opposed to <i>mis-documentated</i> or <i>deprecated</i>) actually refers to quite a large number of different types.<br
/> In the following list, the hyperlinks on the list-item titles lead to a list of corresponding articles on this website:</p><ul><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-function/">Undocumented functions</a></b><br
/> Matlab functions which appears nowhere in the documentation, are usually built-in functions (do not have an m-file) and can only be inferred from online CSSM posts or usage within one of the Matlab m-functions installed with Matlab (the latter being the usual case). None of these functions is officially supported by MathWorks. <a
target="_blank" href="http://undocumentedmatlab.com/blog/category/mex/">MEX</a> is an important source for such functions.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/semi-documented-function/">Semi-documented functions</a></b><br
/> Matlab functionality which exists in Matlab m-functions installed with Matlab, but have their main comment separated from the H1 comment line, thereby hiding it from normal view (via Matlab&#8217;s <i><b>help</b></i> function). The H1 comment line itself is simply a standard warning that this function is not officially supported and may change in some future version. To see the actual help comment, simply edit the function (using Matlab&#8217;s <i><b>edit</b></i> function or any text editor) and place a comment sign (%) at the empty line between the H1 comment and the actual help section. The entire help section will then onward be visible via the <i><b>help</b></i> 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: #080;">&#91;</span>tree, container<span style="color: #080;">&#93;</span> = uitree<span style="color: #080;">&#40;</span><span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
        <span style="color: #228B22;">% WARNING: This feature is not supported in MATLAB</span>
        <span style="color: #228B22;">% and the API and functionality may change in a future release.</span>
<span style="color: #0000FF;">fix</span> =&gt;  <span style="color: #228B22;">%</span>
        <span style="color: #228B22;">% UITREE creates a uitree component with hierarchical data in a figure window.</span>
        <span style="color: #228B22;">%   UITREE creates an empty uitree object with default property values in</span>
        <span style="color: #228B22;">%   a figure window.</span>
        <span style="color: #228B22;">%...</span></pre></div></div><p>These functions are not documented in the full documentation (via Matlab&#8217;s <i><b>doc</b></i> function, or online). The odd thing is that some of these functions may appear in the category help output (for example, <i><b>help</b>(&#8216;uitools&#8217;)</i>), and in some cases may even have a fully-visible help section (e.g., <i><b>help</b>(&#8216;setptr&#8217;)</i>), but do not have any online help documentation (<i><b>docsearch</b>(&#8216;setptr&#8217;)</i> fails, and <i><b>doc</b>(&#8216;setptr&#8217;)</i> simply displays the readable help text).</p><p>All these functions are officially unsupported by MathWorks, even when having a readable help section. The rule of thumb appears to be that a Matlab function is supported only if it has online documentation. Note, however, that in some rare cases a documentation discrepancy may be due to a MathWorks documentation error, not to unsupportability&#8230;</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-function/">Helper functions</a></b><br
/> Many fully-supported Matlab functions use helper functions that have a specific use in the main (documented) function(s).  Often, these helper functions are tightly-coupled to their documented parents and are useless as stand-alone functions. But quite a few of them have quite useful stand-alone use, as I&#8217;ve already shown in some past articles.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-feature/">Undocumented features</a> and <a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-property/">properties</a></b><br
/> Features of otherwise-documented Matlab functions, which appear nowhere in the official documentation. You guessed it – these are also not supported by MathWorks&#8230; Like undocumented functions, you can only infer such features by the occasional CSSM post or a reference somewhere in Matlab&#8217;s m-code.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/semi-documented-feature/">Semi-documented features</a></b><br
/> Features of otherwise-documented Matlab functions, which are documented in a separate section beneath the main help section, and nowhere else (not in the full doc not the online documentation). If you did not know in advance that these features existed, you could only learn of them by manually looking at Matlab&#8217;s m-files (which is what I do in most cases&#8230;).</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-property/">Undocumented properties</a></b><br
/> Many Matlab objects have internal properties, which can be retrieved (via Matlab&#8217;s <i><b>get</b></i> function) and/or set (via the <i><b>set</b></i> function) programmatically. All these properties are fully documented. Many objects also possess hidden properties, some of which are very interesting and useful, but which are undocumented and (oh yes) unsupported. Like undocumented features, they can only be inferred from CSSM or existing code. In a recent <a
target="_blank" href="http://undocumentedmatlab.com/blog/getundoc-get-undocumented-object-properties/">article</a> I described my <i><b>getundoc</b></i> utility, which lists these undocumented properties of specified objects.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/internal-component/">Internal Matlab classes</a></b><br
/> Matlab uses a vast array of specialized Java classes to handle everything from algorithms to GUI. These classes are (of course) undocumented/unsupported. They can often be accessed directly from the Matlab Command Window or user m-files. GUI classes can be inferred by inspecting the figure frame&#8217;s Java components, and non-GUI classes can often be inferred from references in Matlab&#8217;s m-files.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/JMI">Matlab-Java integration</a></b><br
/> Matlab&#8217;s GUI interface, as well as the Java-to-Matlab interface (JMI) is fully undocumented and unsupported. In addition to JMI, there are other mechanisms to run Matlab code from within Java (namely JMI, COM and DDE) &#8211; these are all unsupported and by-and-large undocumented.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/?s=UDD">Matlab&#8217;s UDD mechanism</a></b><br
/> UDD (Unified Data Definition?) is used extensively in Matlab as the internal object-oriented mechanism for describing object properties and functionalities. We can use UDD for a wide variety of uses. UDD was described in a series of articles here in early 2011.</li></ul><p>Next week I will list the reasons that cause MathWorks to decide whether a particular feature or property should be documented or not.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/reasons-for-undocumented-matlab-aspects/' rel='bookmark' title='Reasons for undocumented Matlab aspects'>Reasons for undocumented Matlab aspects</a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-cursorbar-object/' rel='bookmark' title='Undocumented cursorbar object'>Undocumented cursorbar object</a> <small>Matlab's internal undocumented graphics.cursorbar object can be used to present dynamic data-tip cross-hairs...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uiundo-matlab-undocumented-undo-redo-manager/' rel='bookmark' title='uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager'>uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager</a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li><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></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Tri-state checkbox</title><link>http://undocumentedmatlab.com/blog/tri-state-checkbox/</link> <comments>http://undocumentedmatlab.com/blog/tri-state-checkbox/#comments</comments> <pubDate>Wed, 19 Oct 2011 14:04:20 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[UI controls]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[FindJObj]]></category> <category><![CDATA[Internal component]]></category> <category><![CDATA[JIDE]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2467</guid> <description><![CDATA[Matlab checkboxes can easily be made to support tri-state functionality.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/recovering-previous-editor-state/' rel='bookmark' title='Recovering previous editor state'>Recovering previous editor state</a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/determining-axes-zoom-state/' rel='bookmark' title='Determining axes zoom state'>Determining axes zoom state</a> <small>The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object....</small></li><li><a
href='http://undocumentedmatlab.com/blog/jide-property-grids/' rel='bookmark' title='JIDE Property Grids'>JIDE Property Grids</a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li><li><a
href='http://undocumentedmatlab.com/blog/findjobj-gui-display-container-hierarchy/' rel='bookmark' title='FindJObj GUI &#8211; display container hierarchy'>FindJObj GUI &#8211; display container hierarchy</a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>When presenting information visually in graphical user interfaces (GUIs), we often need to present and enable interaction with state data (such as On/Off). In most cases, we would naturally use a checkbox to present the information and enable interaction. But What can we do if the data has three possible states. For example, Yes/No/Maybe, or: Full/Empty/Partial, or: Up/Down/Undetermined ?</p><p>Until today, Matlab GUIs had to resort to using drop-down (aka combo-box or popup-menu) or radio-button controls to present such information. However, would it not be nicer if we could still use a checkbox? Outside Matlab, such a control is known as a tri-state checkbox and many modern GUI frameworks support it. Well, surprise surprise, so does Matlab (although you would never guess it from the documentation).</p><h3 id="CheckBoxTree">CheckBoxTree</h3><p>Last year, I have already <a
target="_blank" href="http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/#Built-in-classes">described</a> a built-in Matlab tree control whose nodes have tri-state checkboxes:</p><p><center><div
class="wp-caption aligncenter" style="width: 321px"><img
alt="a regular MJTree (left) and a CheckBoxTree (right)" src="http://UndocumentedMatlab.com/images/CheckBoxTree.png" title="a regular MJTree (left) and a CheckBoxTree (right)" width="311" height="218" /><p
class="wp-caption-text">a regular MJTree (left) and a CheckBoxTree (right)</p></div></center></p><p>Today I will show how we can use these checkboxes as independent GUI controls.</p><h3 id="uicontrol">Modifying the standard Matlab checkbox uicontrol</h3><p>In order to modify the standard Matlab checkbox <i><b>uicontrol</b></i>, we need to first get its underlying Java component reference. This is done using the <a
target="_blank" href="http://undocumentedmatlab.com/blog/findjobj-find-underlying-java-object/"><i><b>findjobj</b></i> utility</a>. We then update its UI wrapper to be the same as the <code>CheckBoxTree</code>&#8216;s checkbox control.</p><p>To programmatically set a mixed state we update the &#8216;selectionState&#8217; client property to <code>SelectionState.MIXED</code> (<code>SelectionState</code> also has the <code>SELECTED</code> and <code>NOT_SELECTED</code> values).</p><p>Here is an end-to-end example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hCB = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Style'</span>,<span style="color:#A020F0;">'checkbox'</span>, <span style="color: #F0F;">...</span><span style="color: #080;">&#41;</span>;
jCB = findjobj<span style="color: #080;">&#40;</span>hCB<span style="color: #080;">&#41;</span>;
jCB.<span style="">setUI</span><span style="color: #080;">&#40;</span>com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">checkboxtree</span>.<span style="">TriStateButtonUI</span><span style="color: #080;">&#40;</span>jCB.<span style="">getUI</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Update the checkbox state to MIXED</span>
newState = com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">checkboxtree</span>.<span style="">SelectionState</span>.<span style="">MIXED</span>;
jCB.<span style="">putClientProperty</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'selectionState'</span>, newState<span style="color: #080;">&#41;</span>;
jCB.<span style="">repaint</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 299px"><img
alt="Matlab checkboxes displaying mixed states" src="http://UndocumentedMatlab.com/images/CheckBox_TriState.png" title="Matlab checkboxes displaying mixed states" width="289" /><p
class="wp-caption-text">Matlab checkboxes displaying mixed states</p></div></center></p><h3 id="independent">Displaying as an independent Java control</h3><p>Instead of retrofitting a standard Matlab <i><b>uicontrol</b></i> as described above, we can directly use the standard <code>javax.swing.JCheckBox</code> which does not normally support tri-state (it only has two states), displaying it in our GUI with the built-in <a
target="_blank" href="http://undocumentedmatlab.com/blog/javacomponent/"><i><b>javacomponent</b></i> function</a>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Display the checkbox (UNSELECTED state at first)</span>
jCB = javax.<span style="">swing</span>.<span style="">JCheckBox</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'JCheckBox - mixed'</span>,<span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>;
javacomponent<span style="color: #080;">&#40;</span>jCB, <span style="color: #080;">&#91;</span><span style="color: #33f;">10</span>,<span style="color: #33f;">70</span>,<span style="color: #33f;">150</span>,<span style="color: #33f;">20</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Update the checkbox state to MIXED</span>
import com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">checkboxtree</span>.*
jCB.<span style="">setUI</span><span style="color: #080;">&#40;</span>TriStateButtonUI<span style="color: #080;">&#40;</span>jCB.<span style="">getUI</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
jCB.<span style="">putClientProperty</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'selectionState'</span>, SelectionState.<span style="">MIXED</span><span style="color: #080;">&#41;</span>;
jCB.<span style="">repaint</span>;</pre></div></div><p>Note that instead of using <code>javax.swing.JCheckBox</code>, we could use the internal Matlab class <code>com.mathworks.mwswing.MJCheckBox</code>, which directly extends <code>JCheckBox</code> and adds mnemonic (shortcut-key) support, but is otherwise fully compatible with <code>JCheckBox</code>. Actually, it is <code>MJCheckBox</code> which is the underlying Java component of the standard Matlab checkbox <i><b>uicontrol</b></i>.</p><h3 id="alternatives">Alternative controls</h3><p>Now that we have seen that Matlab includes built-in support (well, at least support in the technical sense, not the official customer-support sense), would you be surprised to learn that it includes similar support in other internal components as well?</p><p>The internal Matlab class <code>com.mathworks.mwt.MWCheckbox</code> directly supports a tri-state (yes/no/maybe) checkbox, without any need to update its UI, as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Display the checkbox (UNSELECTED state at first)</span>
jCB = com.<span style="">mathworks</span>.<span style="">mwt</span>.<span style="">MWCheckbox</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'MWCheckbox - mixed'</span>,<span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>;
javacomponent<span style="color: #080;">&#40;</span>jCB, <span style="color: #080;">&#91;</span><span style="color: #33f;">10</span>,<span style="color: #33f;">70</span>,<span style="color: #33f;">150</span>,<span style="color: #33f;">20</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Update the checkbox state to MIXED</span>
jCB.<span style="">setMixedState</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Retrieve the current state</span>
isMixedFlag = jCB.<span style="">isMixedState</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% true/false</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 299px"><img
alt="MJCheckBox vs. MWCheckbox" src="http://UndocumentedMatlab.com/images/CheckBox_MWT_MWSwing.png" title="MJCheckBox vs. MWCheckbox" width="289" /><p
class="wp-caption-text">MJCheckBox vs. MWCheckbox</p></div></center></p><p>Note that the State property, which controls the standard selected/unselected state, is entirely independent from the MixedState property. Both State and MixedState are boolean properties, so to get the actual checkbox state we need to query both of these properties.</p><p>Another internal Matlab class that we can use is JIDE&#8217;s <code>com.jidesoft.swing.TristateCheckBox</code> (which is pre-bundled in Matlab and is fully documented <a
target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/com/jidesoft/swing/TristateCheckBox.html">here</a>).</p><p>There are many other tri-state checkbox alternatives available online (for example, <a
target="_blank" rel="nofollow" href="https://forums.oracle.com/forums/search.jspa?threadID=&#038;q=%28tri-state+OR+tristate%29+AND+checkbox&#038;objID=c285&#038;dateRange=all&#038;userID=&#038;numResults=30&#038;rankBy=10001">here</a>, <a
target="_blank" rel="nofollow" href="http://www.javaspecialists.eu/archive/Issue145.html">here</a> and <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/1263323/tristate-checkboxes-in-java">here</a>). We can easily include them in our Matlab GUI with the <i><b>javacomponent</b></i> function. Using external components we can be more certain of the compatibility issues in past and future Matlab releases. On the other hand, internal Matlab classes do have the advantage of being inherently accessible on all platforms of the same Matlab release, whereas non-Matlab components must be included in our deployment package.</p><p>Do you use any tri-state controls, either Matlab or external, in your work? If so, please share your experience in a <a
href="http://UndocumentedMatlab.com/blog/tri-state-checkbox/#respond">comment below</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/recovering-previous-editor-state/' rel='bookmark' title='Recovering previous editor state'>Recovering previous editor state</a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/determining-axes-zoom-state/' rel='bookmark' title='Determining axes zoom state'>Determining axes zoom state</a> <small>The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object....</small></li><li><a
href='http://undocumentedmatlab.com/blog/jide-property-grids/' rel='bookmark' title='JIDE Property Grids'>JIDE Property Grids</a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li><li><a
href='http://undocumentedmatlab.com/blog/findjobj-gui-display-container-hierarchy/' rel='bookmark' title='FindJObj GUI &#8211; display container hierarchy'>FindJObj GUI &#8211; display container hierarchy</a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/tri-state-checkbox/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> </channel> </rss>

<!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              b7666
Template:           tag
-->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: undocumentedmatlab.com @ 2012-05-21 20:38:15 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/tag/undocumented-feature/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      2.541s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1337657893; expires=Wed, 22-May-2013 03:38:13 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Tue, 22 May 2012 03:38:15 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Tue, 22 May 2012 04:38:15 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               d4aa011f849c9c13fdab8ecb7f880b14
Content-Encoding:   gzip
-->
