<?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; Presumed future risk</title> <atom:link href="http://undocumentedmatlab.com/blog/category/presumed-future-risk/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>6</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>0</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>Customizing menu items part 1</title><link>http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/</link> <comments>http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/#comments</comments> <pubDate>Wed, 25 Apr 2012 18:14:08 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Figure window]]></category> <category><![CDATA[GUI]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[HTML]]></category> <category><![CDATA[Menubar]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2897</guid> <description><![CDATA[Matlab menus can be customized in a variety of undocumented manners - first article of a series.<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-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-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>Over the past years, I have not posted articles dealing with menu items. I have shown how to <a
target="_blank" href="http://undocumentedmatlab.com/blog/modifying-default-toolbar-menubar-actions/">directly access menu items&#8217; hidden handles</a>, but not much more than that. A year ago I <a
target="_blank" href="http://undocumentedmatlab.com/blog/2010-perspective/">promised</a> a mini-series on menu customizations, and it&#8217;s time to keep my promise. In today&#8217;s article, the first in the mini-series, I will present several undocumented menu customization topics that rely on pure-Matlab (i.e, no Java today). The next article in this series will focus on Java-based customizations.</p><h3 id="Invoking">Invoking menu item callbacks</h3><p>As noted above, a figure window&#8217;s menu items can be directly accessed. Once we access a menu item&#8217;s handle, we can extract its <b>Callback</b> property and directly invoke it (for example, using the semi-documented <a
target="_blank" href="http://undocumentedmatlab.com/blog/hgfeval/"><i><b>hgfeval</b></i> function</a>). Note that menu callbacks are kept in <b>Callback</b>, while toolbar callbacks are kept in <b>ClickedCallback</b>.</p><p>Menu callbacks generally use internal <a
target="_blank" href="http://undocumentedmatlab.com/blog/legend-semi-documented-feature/#Semi-documented">semi-documented</a> functions (i.e., having a readable help section but no doc, online help, or official support), which are part of Matlab&#8217;s uitools folder. These functions are specific to each top-level menu tree: <i><b>filemenufcn, editmenufcn, viewmenufcn, insertmenufcn, toolsmenufcn, desktopmenufcn, winmenu</b></i>, and <i><b>helpmenufcn</b></i> implement the figure&#8217;s eight respective top-level menu trees&#8217; callbacks. These functions accept an optional figure handle (otherwise, <i><b>gcbf</b></i> is assumed), followed by a string specifying the specific menu item whose action needs to be run. <i><b>webmenufcn</b></i> implements the Help menu&#8217;s Web Resources sub-menu callbacks in a similar manner.</p><p>Use of these functions makes it easy to invoke a menu action directly from our Matlab code: instead of accessing the relevant menu item and invoking its <b>Callback</b>, we simply find out the menu item string in advance and use it directly. For example,</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">filemenufcn FileClose;
editmenufcn<span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'EditPaste'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><i><b>uimenufcn</b></i> is a related fully-undocumented (built-in) function, available since Matlab R11 (late 1990s). It accepts a figure handle (or the zero [0] handle to indicate the desktop) and action name. For example, the fully-documented <i><b>commandwindow</b></i> function uses the following code to bring the Command Window into focus:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">uimenufcn<span style="color: #080;">&#40;</span><span style="color: #33f;">0</span>, <span style="color:#A020F0;">'WindowCommandWindow'</span><span style="color: #080;">&#41;</span>;</pre></div></div><h3 id="Uitools">Customizing menus via uitools</h3><p><i><b>makemenu</b></i> is another semi-documented uitool function that enables easy creation of hierarchical menu trees with separators and accelerators. It is a simple and effective wrapper for <i><b>uimenu</b></i>. <i><b>makemenu</b></i> is a useful function that has been made obsolete (grandfathered) without any known replacement.</p><p><i><b>makemenu</b></i> accepts four parameters: a figure handle, a char matrix of labels (&#8216;&gt;&#8217; indicating sub item, &#8216;&gt;&gt;&#8217; indicating sub-sub items etc.; &#8216;&amp;&#8217; indicating keyboard shortcut; &#8216;^x&#8217; indicating an accelerator key; &#8216;-&#8217; indicating a separator line), a char matrix of callbacks, and an optional char matrix of tags (empty by default). <i><b>makemenu</b></i> makes use of another semi-documented grandfathered function, <i><b>menulabel</b></i>, to parse the specified label components. <i><b>makemenu</b></i> returns an array of handles of the created <i><b>uimenu</b></i> items:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">labels = str2mat<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'&amp;File'</span>, <span style="color: #F0F;">...</span>    <span style="color: #228B22;">% File top menu</span>
           <span style="color:#A020F0;">'&gt;&amp;New^n'</span>, <span style="color: #F0F;">...</span>           <span style="color: #228B22;">% File=&gt;New</span>
           <span style="color:#A020F0;">'&gt;&amp;Open'</span>, <span style="color: #F0F;">...</span>            <span style="color: #228B22;">% File=&gt;Open</span>
           <span style="color:#A020F0;">'&gt;&gt;Open &amp;document^d'</span>, <span style="color: #F0F;">...</span>    <span style="color: #228B22;">% File=&gt;Open=&gt;doc</span>
           <span style="color:#A020F0;">'&gt;&gt;Open &amp;graph^g'</span>, <span style="color: #F0F;">...</span>       <span style="color: #228B22;">% File=&gt;Open=&gt;graph</span>
           <span style="color:#A020F0;">'&gt;-------'</span>, <span style="color: #F0F;">...</span>          <span style="color: #228B22;">% File=&gt;separator line</span>
           <span style="color:#A020F0;">'&gt;&amp;Save^s'</span>, <span style="color: #F0F;">...</span>          <span style="color: #228B22;">% File=&gt;Save</span>
           <span style="color:#A020F0;">'&amp;Edit'</span>, <span style="color: #F0F;">...</span>		<span style="color: #228B22;">% Edit top menu</span>
           <span style="color:#A020F0;">'&amp;View'</span>, <span style="color: #F0F;">...</span>		<span style="color: #228B22;">% View top menu</span>
           <span style="color:#A020F0;">'&gt;&amp;Axis^a'</span>, <span style="color: #F0F;">...</span>          <span style="color: #228B22;">% View=&gt;Axis</span>
           <span style="color:#A020F0;">'&gt;&amp;Selection region^r'</span><span style="color: #080;">&#41;</span>; <span style="color: #228B22;">% View=&gt;Selection</span>
calls = str2mat<span style="color: #080;">&#40;</span><span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>		<span style="color: #228B22;">% no action: File top menu</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'New'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: Open sub-menu</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'Open doc'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'Open graph'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: Separator</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'Save'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: Edit top menu</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: View top menu</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'View axis'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'View selection region'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
handles = makemenu<span style="color: #080;">&#40;</span>hFig, labels, calls<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'menuBar'</span>,<span style="color:#A020F0;">'none'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 277px"><img
alt="A simple figure menu" src="http://UndocumentedMatlab.com/images/makemenu.png" title="A simple figure menu" width="267" height="148"/><p
class="wp-caption-text">A simple figure menu</p></div></center></p><h3 id="HTML">Customizing menus via HTML</h3><p>Since menu items share the same <a
target="_blank" href="http://undocumentedmatlab.com/blog/html-support-in-matlab-uicomponents/">HTML/CSS support feature</a> as all Java Swing labels, we can specify font size/face/color, bold, italic, underline, superscript/subscript, and practically any HTML formatting.</p><p>Note that some features, such as the font or foreground/background colors, have specific properties that we can set using the Java handle, instead of using HTML. The benefit of using HTML is that it enables setting all the formatting in a single property. HTML does not require using Java – just pure Matlab (see the following example).</p><p>Multi-line menu items can easily be done with HTML: simply include a <code>&lt;br&gt;</code> element in the label – the menu item will split into two lines and automatically resize vertically when displayed:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">txt1 = <span style="color:#A020F0;">'&lt;html&gt;&lt;b&gt;&lt;u&gt;&lt;i&gt;Save&lt;/i&gt;&lt;/u&gt;'</span>;
txt2 = <span style="color:#A020F0;">'&lt;font color=&quot;red&quot;&gt;&lt;sup&gt;this file&lt;/sup&gt;&lt;/font&gt;&lt;/b&gt;&lt;/html&gt;'</span>;
txt3 = <span style="color:#A020F0;">'&lt;br /&gt;this file as...'</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;">'Label'</span>,<span style="color: #080;">&#91;</span>txt1,txt2<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</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;">'figMenuFileSaveAs'</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'Label'</span>,<span style="color: #080;">&#91;</span>txt1,txt3<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 195px"><img
alt="A multi-line HTML-rendered menu item" src="http://UndocumentedMatlab.com/images/uimenu2.png" title="A multi-line HTML-rendered menu item" width="185" height="184"/><p
class="wp-caption-text">A multi-line HTML-rendered menu item</p></div></center></p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hMenuItem, <span style="color:#A020F0;">'Label'</span>,<span style="color: #080;">&#91;</span><span style="color:#A020F0;">'&lt;html&gt;&amp;2: C:\My Documents\doc.txt&lt;br /&gt;'</span>
   <span style="color:#A020F0;">'&lt;font size=&quot;-1&quot; face=&quot;Courier New&quot; color=&quot;red&quot;&gt;&amp;nbsp;&amp;nbsp; '</span>
   <span style="color:#A020F0;">'Date: 15-Jun-2011 13:23:45&lt;br /&gt;&amp;nbsp;&amp;nbsp; Size: 123 KB&lt;/font&gt;&lt;/html&gt;'</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 421px"><img
alt="HTML-rendered menu items" src="http://UndocumentedMatlab.com/images/uimenu2b.png" title="HTML-rendered menu items" width="411" height="246"/><p
class="wp-caption-text">HTML-rendered menu items</p></div></center></p><p>Much more complex customizations can be achieved using Java. So stay tuned to part 2 of this mini-series&#8230;</p><p>Note: Menu customization is explored in depth in section 4.6 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">book</a>.</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-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-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-1/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Setting axes tick labels format</title><link>http://undocumentedmatlab.com/blog/setting-axes-tick-labels-format/</link> <comments>http://undocumentedmatlab.com/blog/setting-axes-tick-labels-format/#comments</comments> <pubDate>Wed, 18 Apr 2012 18:00:17 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Handle graphics]]></category> <category><![CDATA[Listeners]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Undocumented function]]></category> <category><![CDATA[Listener]]></category> <category><![CDATA[Pure Matlab]]></category> <category><![CDATA[schema.prop]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2856</guid> <description><![CDATA[Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/axes-looseinset-property/' rel='bookmark' title='Axes LooseInset property'>Axes LooseInset property</a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li><li><a
href='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/fig-files-format/' rel='bookmark' title='FIG files format'>FIG files format</a> <small>FIG files are actually MAT files in disguise. This article explains how this can be useful in Matlab applications....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Have you ever tried to customize the way in which tick labels appear in Matlab plot axes?</p><p>For example, setting the numerical precision of the labels, or adding some short descriptive text (for example, the units)? If you have, then I bet that you have encountered the following dilemma: Once we modify the tick labels (for discussion sake, let&#8217;s assume the Y axis, so this is done by updating the <b>YTickLabel</b> property), then the corresponding <b>YTickLabelMode</b> property changes from &#8216;auto&#8217; to &#8216;manual&#8217; and loses its relationship to the tick values (<b>YTick</b>). So, if we now zoom or pan the plot, our new labels remain unchanged although the tick values have changed, causing much panic and frustration&#8230; If we also set the tick values manually, this solves <i>that</i> problem but leaves us with another: now, when we zoom or pan, we no longer see any ticks or tick labels at all!</p><p><center><div
class="wp-caption aligncenter" style="width: 460px"><img
src="http://UndocumentedMatlab.com/images/PlotLabels_orig.png" alt="Original plot" title="Original plot" width="134" height="143" /> <img
src="http://UndocumentedMatlab.com/images/PlotLabels_1b.png" alt="Manual labels, auto ticks" title="Manual labels, auto ticks" width="134" height="143" /> <img
src="http://UndocumentedMatlab.com/images/PlotLabels_1c.png" alt="Manual labels, manual ticks" title="Manual labels, manual ticks" width="134" height="143" /><p
class="wp-caption-text">Original plot (left)<br
/>Manual labels, auto ticks (center)<br
/>Manual labels, manual ticks (right)</p></div></center></p><p>Of course, we can always trap the zoom and pan callback functions to update the tick labels dynamically while keeping the tick values automatically. This will work for these cases, but we need to do it separately for zoom and pan. Also, if we modify the axes limits explicitly (via the corresponding <b>YLim</b> property) or indirectly (by modifying the displayed plot data), then the callbacks are not called and the labels are not updated.</p><h3 id="solution">The solution &#8211; using a property change listener</h3><p>A better way to solve this problem is to simply trap changes to the displayed tick values, and whenever these occur to call our dedicated function to update the labels according to the new tick values. This can be done by using UDD, or more precisely the <a
target="_blank" href="http://undocumentedmatlab.com/blog/udd-events-and-listeners/">ability to trap update events on any property</a> (in our case, <b>YTick</b>). Such a mechanism was already <a
target="_blank" href="http://undocumentedmatlab.com/blog/continuous-slider-callback/#Property_Listener">demonstrated here</a> in 2010, as one way to achieve continuous slider feedback. The idea is to use the built-in <i><b>handle.listener</b></i> function with the PropertyPostSet event, as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hhAxes = handle<span style="color: #080;">&#40;</span>hAxes<span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% hAxes is the Matlab handle of our axes</span>
hProp = <span style="color: #0000FF;">findprop</span><span style="color: #080;">&#40;</span>hhAxes,<span style="color:#A020F0;">'YTick'</span><span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% a schema.prop object</span>
hListener = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>hhAxes, hProp, <span style="color:#A020F0;">'PropertyPostSet'</span>, @myCallbackFunction<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span>hAxes, <span style="color:#A020F0;">'YTickListener'</span>, hListener<span style="color: #080;">&#41;</span>;</pre></div></div><p>Note that we have used <i><b>setappdata</b></i> to store the <code>hListener</code> handle in the axes. This ensures that the listener exists for exactly as long as the axes does. If we had not stored this listener handle somewhere, then Matlab would have immediately deleted the listener hook and our callback function would not have been called upon tick value updates. Forgetting to store listener handles is a common pitfall when using them. If you take a look at the <i><b>addlistener</b></i> function&#8217;s code, you will see that it also uses <i><b>setappdata</b></i> after creating the listener, for exactly this reason. Unfortunately, <i><b>addlistsner</b></i> cannot always be used, and I keep forgetting under which circumstances, so I generally use <i><b>handle.listener</b></i> directly as above: It&#8217;s simple enough to use that I find I never really need to use the simple <i><b>addlistener</b></i> wrapper, but you are welcome to try it yourself.</p><p>That&#8217;s all there is to it: Whenever <b>YTick</b> changes its value(s), our callback function (<i>myCallbackFunction</i>) will automatically be called. It is quite simple to set up. While we cannot use TeX in tick labels yet (this will change in the upcoming <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-hg2/">HG2</a>), using <i><b>sprintf</b></i> formatting does enable quite a bit of flexibility in formatting the labels. For example, let&#8217;s say I want my tick labels to have the format &#8216;%.1fV&#8217; (i.e., always one decimal, plus the Volts units):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> myCallbackFunction<span style="color: #080;">&#40;</span>hProp,eventData<span style="color: #080;">&#41;</span>    <span style="color: #228B22;">%#ok - hProp is unused</span>
   hAxes = eventData.<span style="">AffectedObject</span>;
   tickValues = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hAxes,<span style="color:#A020F0;">'YTick'</span><span style="color: #080;">&#41;</span>;
   newLabels = arrayfun<span style="color: #080;">&#40;</span>@<span style="color: #080;">&#40;</span>value<span style="color: #080;">&#41;</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'%.1fV'</span>,value<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>, tickValues, <span style="color:#A020F0;">'UniformOutput'</span>,<span style="color: #0000FF;">false</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hAxes, <span style="color:#A020F0;">'YTickLabel'</span>, newLabels<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>  <span style="color: #228B22;">% myCallbackFunction</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 310px"><img
src="http://UndocumentedMatlab.com/images/PlotLabels_2a.png" alt="Manual labels, automatically updated" title="Manual labels, automatically updated" width="134" height="143" /> <img
src="http://UndocumentedMatlab.com/images/PlotLabels_2b.png" alt="Manual labels, automatically updated" title="Manual labels, automatically updated" width="134" height="143" /><p
class="wp-caption-text">Manual labels, automatically updated</p></div></center></p><h3 id="duplicates">Handling duplicate tick labels</h3><p>Of course, &#8216;%.1fV&#8217; may not be a good format when we zoom in to such a degree that the values differ by less than 0.1 &#8211; in this case all the labels will be the same. So let&#8217;s modify our callback function to add extra decimals until the labels become distinct:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> myCallbackFunction<span style="color: #080;">&#40;</span>hProp,eventData<span style="color: #080;">&#41;</span>    <span style="color: #228B22;">%#ok - hProp is unused</span>
   hAxes = eventData.<span style="">AffectedObject</span>;
   tickValues = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hAxes,<span style="color:#A020F0;">'YTick'</span><span style="color: #080;">&#41;</span>;
&nbsp;
   <span style="color: #228B22;">%newLabels = arrayfun(@(value)(sprintf('%.1fV',value)), tickValues, 'UniformOutput',false);</span>
   digits = <span style="color: #33f;">0</span>;
   labelsOverlap = <span style="color: #0000FF;">true</span>;
   <span style="color: #0000FF;">while</span> labelsOverlap
      <span style="color: #228B22;">% Add another decimal digit to the format until the labels become distinct</span>
      digits = digits + <span style="color: #33f;">1</span>;
      <span style="color: #0000FF;">format</span> = <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'%%.%dfV'</span>,digits<span style="color: #080;">&#41;</span>;
      newLabels = arrayfun<span style="color: #080;">&#40;</span>@<span style="color: #080;">&#40;</span>value<span style="color: #080;">&#41;</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">format</span>,value<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>, tickValues, <span style="color:#A020F0;">'UniformOutput'</span>,<span style="color: #0000FF;">false</span><span style="color: #080;">&#41;</span>;
      labelsOverlap = <span style="color: #080;">&#40;</span><span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>newLabels<span style="color: #080;">&#41;</span> &gt; <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">unique</span><span style="color: #080;">&#40;</span>newLabels<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
      <span style="color: #228B22;">% prevent endless loop if the tick values themselves are non-unique</span>
      <span style="color: #0000FF;">if</span> labelsOverlap <span style="color: #F0F;">&amp;&amp;</span> <span style="color: #0000FF;">max</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">diff</span><span style="color: #080;">&#40;</span>tickValues<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>&lt; <span style="color: #33f;">16</span>*<span style="color: #0000FF;">eps</span>
         <span style="color: #0000FF;">break</span>;
      <span style="color: #0000FF;">end</span>
   <span style="color: #0000FF;">end</span>
&nbsp;
   <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hAxes, <span style="color:#A020F0;">'YTickLabel'</span>, newLabels<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>  <span style="color: #228B22;">% myCallbackFunction</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 310px"><img
src="http://UndocumentedMatlab.com/images/PlotLabels_3a.png" alt="non-distinct labels" title="non-distinct labels" width="134" height="143" /> <img
src="http://UndocumentedMatlab.com/images/PlotLabels_3b.png" alt="distinct labels" title="distinct labels" width="134" height="143" /><p
class="wp-caption-text">Non-distinct labels &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; distinct labels</p></div></center></pre><h3 id="ticklabelformat"><i>ticklabelformat</i></h3><p>Based on a file that I received from an anonymous reader a few years ago, I have prepared a utility called <i><b>ticklabelformat</b></i> that automates much of the set-up above. Feel free to <a
target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/36254-ticklabelformat">download</a> this utility and modify it for your needs - it's quite simple to read and follow. The usage syntax is as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">ticklabelformat<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'y'</span>,<span style="color:#A020F0;">'%.6g V'</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% sets y axis on current axes to display 6 significant digits</span>
ticklabelformat<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'xy'</span>,<span style="color:#A020F0;">'%.2f'</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% sets x &amp; y axes on current axes to display 2 decimal digits</span>
ticklabelformat<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'z'</span>,@myCbFcn<span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% sets a function to update the Z tick labels on current axes</span>
ticklabelformat<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'z'</span>,<span style="color: #080;">&#123;</span>@myCbFcn,extraData<span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% sets an update function as above, with extra data</span></pre></div></div><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/axes-looseinset-property/' rel='bookmark' title='Axes LooseInset property'>Axes LooseInset property</a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li><li><a
href='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/fig-files-format/' rel='bookmark' title='FIG files format'>FIG files format</a> <small>FIG files are actually MAT files in disguise. This article explains how this can be useful in Matlab applications....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/setting-axes-tick-labels-format/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Specialized Matlab plots</title><link>http://undocumentedmatlab.com/blog/specialized-matlab-plots/</link> <comments>http://undocumentedmatlab.com/blog/specialized-matlab-plots/#comments</comments> <pubDate>Wed, 11 Apr 2012 17:25:15 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[File Exchange]]></category> <category><![CDATA[JFreeChart]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2849</guid> <description><![CDATA[The new MathWorks Plot Gallery provides access to some plotting examples on the File Exchange. Numerous others are available, extending the customizability of Matlab graphics.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jfreechart-graphs-and-gauges/' rel='bookmark' title='JFreeChart graphs and gauges'>JFreeChart graphs and gauges</a> <small>JFreeChart is an open-source charting library that can easily be integrated in Matlab...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-layout-managers-uicontainer-and-relatives/' rel='bookmark' title='Matlab layout managers: uicontainer and relatives'>Matlab layout managers: uicontainer and relatives</a> <small>Matlab contains a few undocumented GUI layout managers, which greatly facilitate handling GUI components in dynamically-changing figures....</small></li><li><a
href='http://undocumentedmatlab.com/blog/html-support-in-matlab-uicomponents/' rel='bookmark' title='HTML support in Matlab uicomponents'>HTML support in Matlab uicomponents</a> <small>Matlab uicomponents support HTML and CSS, enabling colored items, superscript/subscript, fonts, bold/italic/underline and many other modifications...</small></li><li><a
href='http://undocumentedmatlab.com/blog/spicing-up-matlab-uicontrol-tooltips/' rel='bookmark' title='Spicing up Matlab uicontrol tooltips'>Spicing up Matlab uicontrol tooltips</a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>A few weeks ago, MathWorks has added a new section on its website called the &#8220;<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/discovery/gallery.html">Plot Gallery</a>&#8220;. This section highlights specialized Matlab plots that were posted on the Matlab File Exchange (FEX) and can be used by Matlab users in their GUIs. Unfortunately, for the moment this list only includes some 20 customized plots posted by MathWorks employees, in addition to some 50 examples of using the standard Matlab plots. I have a suspicion that one day, if this proves popular, we will find the gallery integrated in the main Matlab Desktop, possibly next to the current <a
target="_blank" href="http://undocumentedmatlab.com/blog/plot-type-selection-components/">plot selector component</a>.</p><p>Since the Plot Gallery section is a new effort at reducing plotting complexity to Matlab users, I think that it should be encouraged by user feedback. Please feel free to leave them a comment with your feedback, either <a
href="http://undocumentedmatlab.com/blog/specialized-matlab-plots/#respond">on this page</a>, or on their semi-official blog <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/pick/2012/03/23/matlab-plot-gallery/">announcement page</a>.</p><p>My personal beef with the new Plot Gallery is the fact that it does not currently include user submissions. FEX actually contains numerous user-submitted specialized plotting utilities, answering a wide variety of needs in multiple discipline fields. These can easily be found using FEX&#8217;s search functionality or tags. For example, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/?term=tag%3A%22plot%22">the FEX &#8220;plot&#8221; tag</a> currently has 440 separate submissions. Perhaps one day these user submissions will be added to the Plot Gallery in some searchable structured manner.</p><p>One set of specialized plots that I&#8217;d like to highlight today is based on the open-source JFreeChart, that I have <a
target="_blank" href="http://undocumentedmatlab.com/blog/jfreechart-graphs-and-gauges/">described here</a> last year. Sven Körner has used this to <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/?term=authorid%3A92825+JFreeChart">provide</a> a dozen different customized Matlab plots, a few of which can be seen below, showing the power of integrating external code in Matlab GUI. JFreeChart contains many more customizable chart, plot and gauge types so Sven&#8217;s examples should merely be considered as appetizers:</p><p><center><div
class="wp-caption aligncenter" style="width: 310px"><img
alt="MATLAB-integrated dial gauge chart" src="http://UndocumentedMatlab.com/images/dialdemo4_300.jpg" title="MATLAB-integrated dial gauge chart" width="300" height="407"/><p
class="wp-caption-text">MATLAB-integrated dial gauge chart</p></div><br
/><div
class="wp-caption aligncenter" style="width: 410px"><img
alt="MATLAB-integrated multi-axes chart" src="http://UndocumentedMatlab.com/images/multipleAxis_400.jpg" title="MATLAB-integrated multi-axes chart" width="400" height="406"/><p
class="wp-caption-text">MATLAB-integrated multi-axes chart</p></div><br
/></center></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jfreechart-graphs-and-gauges/' rel='bookmark' title='JFreeChart graphs and gauges'>JFreeChart graphs and gauges</a> <small>JFreeChart is an open-source charting library that can easily be integrated in Matlab...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-layout-managers-uicontainer-and-relatives/' rel='bookmark' title='Matlab layout managers: uicontainer and relatives'>Matlab layout managers: uicontainer and relatives</a> <small>Matlab contains a few undocumented GUI layout managers, which greatly facilitate handling GUI components in dynamically-changing figures....</small></li><li><a
href='http://undocumentedmatlab.com/blog/html-support-in-matlab-uicomponents/' rel='bookmark' title='HTML support in Matlab uicomponents'>HTML support in Matlab uicomponents</a> <small>Matlab uicomponents support HTML and CSS, enabling colored items, superscript/subscript, fonts, bold/italic/underline and many other modifications...</small></li><li><a
href='http://undocumentedmatlab.com/blog/spicing-up-matlab-uicontrol-tooltips/' rel='bookmark' title='Spicing up Matlab uicontrol tooltips'>Spicing up Matlab uicontrol tooltips</a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/specialized-matlab-plots/feed/</wfw:commentRss> <slash:comments>5</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>Expanding urlread capabilities</title><link>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/</link> <comments>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/#comments</comments> <pubDate>Wed, 21 Mar 2012 18:00:01 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Jim Hokanson]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2808</guid> <description><![CDATA[The built-in urlread functions has severe limitations. This article explains how to solve them.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/undocumented-xml-functionality/' rel='bookmark' title='Undocumented XML functionality'>Undocumented XML functionality</a> <small>Matlab's built-in XML-processing functions have several undocumented features that can be used by Java-savvy users...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-robot/' rel='bookmark' title='GUI automation using a Robot'>GUI automation using a Robot</a> <small>This article explains how Java's Robot class can be used to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-utilities/' rel='bookmark' title='GUI automation utilities'>GUI automation utilities</a> <small>This article explains a couple of Matlab utilities that use Java's Robot class to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://sites.google.com/site/jimhokanson/">Jim Hokanson</a>. Today, Jim will explain some of the limitations that at one time or another many of us have encountered with Matlab&#8217;s built-in <b>urlread</b> function. More importantly, Jim has spent a lot of time in creating an expanded-capabilities Matlab function, which he explains below. Note that while <b>urlread</b>&#8216;s internals are undocumented, the changes outlined below rely on pretty standard Java and HTTP, and should therefore be quite safe to use on multiple Matlab versions.</i></p><h3 id="Abstract">Abstract</h3><p>I recently tried to implement the <a
target="_blank" rel="nofollow" href="http://dev.mendeley.com">Mendeley</a> API but quickly found that <i><b>urlread</b></i> was not going to be sufficient for my needs. The first indication of this was my inability to send the proper authorization information for POST requests. It became even more obvious with the need to perform DELETE and PUT methods, since <i><b>urlread</b></i> only supports GET and POST. My implementation of <i><b>urlread</b></i>, which I refer to as <i><b>urlread2</b></i>, addresses these and a couple of other issues and can be <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/35693-urlread2">found on the Matlab File Exchange</a>. Other developers have tackled <i><b>urlread</b></i>&#8216;s shortcomings (<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/8474-rewrites-of-urlread-and-urlwrite">this example</a> added timeout support, and <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/27189-urlreadpost-url-post-method-with-binary-file-uploading">this example</a> added support for binary file upload) &#8211; today&#8217;s article will focus on my solution, but others are obviously possible.</p><h3 id="Introduction">Introduction</h3><p><a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">HTTP</a> is the underlying computer networking protocol that enables us to read webpages on the Internet. It consists of a request made by the user to an Internet server (typically located via <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Uniform_resource_locator">URL</a>), and a response from that server. Importantly, the request and response consist of three main parts: a resource line (for requests) or status line (for responses), followed by headers, and optionally a message body.</p><p>Matlab&#8217;s built-in <i><b>urlread</b></i> function enables Matlab users to easily read the server&#8217;s response text into a Matlab string:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">text = urlread<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'http://www.google.com'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This is done internally using Java code that connects to the specified URL and reads the information sent by the URL&#8217;s server (<a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/networking/urls/index.html">more on this</a>).</p><p><i><b>urlread</b></i> accepts optional additional inputs specifying the request type (&#8216;get&#8217; or &#8216;post&#8217;) and parameter values for the request.</p><p>Unfortunately, <i><b>urlread</b></i> has the following limitations:</p><ol><li>It does not allow specification of request headers</li><li>It makes assumptions as to the request headers needed based on the input method</li><li>It does not expose the response headers and status line</li><li>It assumes the response body contains text, and not a binary payload</li><li>It does not enable uploading binary contents to the server</li><li>It does not enable specifying a timeout in case the server is not responding</li></ol><h3 id="urlread2">urlread2</h3><p>The <i><b>urlread2</b></i> function addresses all of these problems. The overall design decision for this function was to make it more general, requiring more work up front to use in some cases, but more flexibility.</p><p>For reference, the following is the calling format for <i><b>urlread2</b></i> (which is reminiscent of <i><b>urlread</b></i>&#8216;s):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">urlread2<span style="color: #080;">&#40;</span>url,*method,*body,*headersIn, <span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span></pre></div></div><p>The * indicate optional inputs that must be spatially maintained.</p><ul><li>url &#8211; (string), url to request</li><li>method &#8211; (string, default GET) HTTP request method</li><li>body &#8211; (string, default &#8221;), body of the request</li><li>headersIn &#8211; (structure, default []), see the following section</li><li>varargin &#8211; extra properties that need to be specified via property/pair values</li></ul><h3 id="Headers">Addressing Problem 1 &#8211; Request header</h3><p><i><b>urlread</b></i> internally uses a Java object called <code>urlConnection</code> that is generally an instance of the class <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html"><code>sun.net.www.protocol.http.HttpURLConnection</code></a>. The method <i>setRequestProperty()</i> can be used to set headers for the request. This method has two inputs, the header name and the value of that header. A simple example of this can be seen below:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">urlConnection.<span style="">setRequestProperty</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Content-Type'</span>,<span style="color:#A020F0;">'application/x-www-form-urlencoded'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Here &#8216;Content-Type&#8217; is the header name and the second input is the value of that property. My function requires passing in nearly all headers as a structure array, with fields for the name and value. The preceding header would be created using a helper function <i><b>http_createHeader.m</b></i>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">header = http_createHeader<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Content-Type'</span>,<span style="color:#A020F0;">'application/x-www-form-urlencoded'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Multiple headers can be passed in to the function by concatenating header structures into a structure array.</p><h3 id="Parameters">Addressing Problem 2 &#8211; Request parameters</h3><p>When making a POST request, parameters are generally specified in the message body using the following format:</p><p><code>[property]=[value]&#038;[property]=[value]</code></p><p>The properties and values are also encoded in a particular way, generally termed <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Percent-encoding">urlencoded</a> (encoding and decoding can be done using Matlab&#8217;s built-in <i><b>urlencode</b></i> and <i><b>urldecode</b></i> functions). For GET requests this string is appended to the url with the &#8220;?&#8221; symbol. Since urlencoding methods can vary, and in the spirit of reducing assumptions, I use separate functions to generate these strings outside of <i><b>urlread2</b></i>, and then pass the result in either as the url (for GET) or as the body input (for POST). As an example, I might <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/?search_submit=fileexchange&#038;term=undocumented+matlab&#038;query=undocumented+matlab">search the Mathworks website</a> using the upper right search bar on its site for &#8220;undocumented matlab&#8221; under file exchange (<i>hmmm&#8230; pretty cute stuff there!</i>). Doing this performs a GET request with the following property/value pairs:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">params = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'search_submit'</span>,<span style="color:#A020F0;">'fileexchange'</span>, <span style="color:#A020F0;">'term'</span>,<span style="color:#A020F0;">'undocumented matlab'</span>, <span style="color:#A020F0;">'query'</span>,<span style="color:#A020F0;">'undocumented matlab'</span><span style="color: #080;">&#125;</span>;</pre></div></div><p>These property/value pairs are somewhat obvious from looking at the URL, but could also be determined by using programs such as <a
target="_blank" rel="nofollow" href="http://www.fiddler2.com/fiddler2/">Fiddler</a>, <a
target="_blank" rel="nofollow" href="http://getfirebug.com/">Firebug</a>, or <a
target="_blank" rel="nofollow" href="http://www.httpwatch.com/">HttpWatch</a>.</p><p>After urlencoding and concatenating, we would form the following string:</p><p><code>search_submit=fileexchange&#038;term=undocumented+matlab&#038;query=undocumented+matlab</code></p><p>This functionality is normally accomplished internally in <i><b>urlread</b></i>, but I use a function <i><b>http_paramsToString</b></i> to produce that result. That function also returns the required header for POST requests. The following is an example of both GET and POST requests:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #080;">&#91;</span>queryString,header<span style="color: #080;">&#93;</span> = http_paramsToString<span style="color: #080;">&#40;</span>params,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% For GET:</span>
url = <span style="color: #080;">&#91;</span>url <span style="color:#A020F0;">'?'</span> queryString<span style="color: #080;">&#93;</span>;
urlread2<span style="color: #080;">&#40;</span>url<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">% For POST:</span>
urlread2<span style="color: #080;">&#40;</span>url,<span style="color:#A020F0;">'POST'</span>,queryString,header<span style="color: #080;">&#41;</span></pre></div></div><h3 id="Response">Addressing Problem 3 &#8211; Response header</h3><p>According to the HTTP protocol, each server response starts with a simple header that indicates a numeric <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes">response status</a>. The following Matlab code provides access to the status line using the <code>urlConnection</code> object:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">status = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'value'</span>,urlConnection.<span style="">getResponseCode</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'msg'</span>,<span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getResponseMessage</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
status = 
    value<span style="color: #F0F;">:</span> <span style="color: #33f;">200</span>
      msg<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'OK'</span></pre></div></div><p><code>urlConnection</code>&#8216;s <i>getHeaderField()</i> and <i>getHeaderFieldKey()</i> methods enable reading the specific parts of the response header:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">headerValue = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getHeaderField</span><span style="color: #080;">&#40;</span>headerIndex<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
headerName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getHeaderFieldKey</span><span style="color: #080;">&#40;</span>headerIndex<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><code>headerIndex</code> starts at 0 and increases by 1 until both <code>headerValue</code> and <code>headerName</code> return empty.</p><p>It is important to note that header keys (names) can be repeated for different values. Sometimes this is desired, such as if there are multiple cookies being sent to the user. To generically handle this case, two header structures are returned. In both cases the header names are the field names in the structure, after <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/genvarname.html">replacing hyphens with underscores</a>. In one case, allHeaders, the values are cell arrays of strings containing all values presented with the particular key. The other structure, firstHeaders, contains only the first instance of the header as a string to avoid needing to dereference a cell array.</p><h3 id="Body">Addressing Problem 4 &#8211; Response body</h3><p><i><b>urlread</b></i> assumes text output. This is fine for most webpages, which use HTML and are therefore text-based. However, <i><b>urlread</b></i> fails when trying to download any non-text resource such as an image, a ZIP file, or a PDF document. I have added a flag in <i><b>urlread2</b></i> called CAST_OUTPUT, which defaults to true, i.e. text response, just as <i><b>urlread</b></i> assumes. Using <i><b>varargin</b></i>, this flag can be set to false ({&#8216;CAST_OUTPUT&#8217;,false}) to indicate a binary response.</p><h3 id="Summary">Summary</h3><p><i><b>urlread2</b></i>&#8216;s functionality has been expanded to also address other limitations of <i><b>urlread</b></i>: It enables binary inputs, better character-set handling of the output, redirection following, and read timeouts.</p><p>The modifications described above provide direct access to the key components of the HTTP request and response messages. Its more generic nature lets <i><b>urlread2</b></i> focus on HTTP transmission, and leaves request formation and response interpretation up to the user. I think ultimately this approach is better than providing one-off modifications of the original <i><b>urlread</b></i> function to suit a particular need. <i><b>urlread2</b></i> and supporting files can be <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/35693-urlread2">found</a> on the Matlab File Exchange.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/undocumented-xml-functionality/' rel='bookmark' title='Undocumented XML functionality'>Undocumented XML functionality</a> <small>Matlab's built-in XML-processing functions have several undocumented features that can be used by Java-savvy users...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-robot/' rel='bookmark' title='GUI automation using a Robot'>GUI automation using a Robot</a> <small>This article explains how Java's Robot class can be used to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-utilities/' rel='bookmark' title='GUI automation utilities'>GUI automation utilities</a> <small>This article explains a couple of Matlab utilities that use Java's Robot class to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Matlab&#8217;s internal memory representation</title><link>http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/</link> <comments>http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/#comments</comments> <pubDate>Thu, 15 Mar 2012 18:11:23 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Mex]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Peter Li]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2798</guid> <description><![CDATA[Matlab's internal memory structure is explored and discussed.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/' rel='bookmark' title='Matlab mex in-place editing'>Matlab mex in-place editing</a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-properties/' rel='bookmark' title='UDD Properties'>UDD Properties</a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>Once again I&#8217;d like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://absurdlycertain.blogspot.com/">Peter Li</a>. Peter wrote about <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/">Matlab Mex in-place editing</a> last month. Today, Peter pokes around in Matlab&#8217;s internal memory representation to the greater good and glory of Matlab Mex programming.</i></p><p><b><i>Disclaimer: The information in this article is provided for informational purposes only.  Be aware that poking into Matlab&#8217;s internals is not condoned or supported by MathWorks, and is not recommended for any regular usage.  Poking into memory has the potential to crash your computer so save your data!  Moreover, be advised (as the text below will show) that the information is highly prone to change without any advance notice in future Matlab releases, which could lead to very adverse effects on any program that relies on it. On the scale of undocumented Matlab topics, this practically breaks the scale, so be EXTREMELY careful when using this.</i></b></p><p>A few weeks ago I <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/">discussed</a> Matlab&#8217;s copy-on-write mechanism as part of my discussion of editing Matlab arrays in-place.  Today I want to explore some behind-the-scenes details of how the copy-on-write mechanism is implemented.  In the process we will learn a little about Matlab&#8217;s internal array representation.  I will also introduce some simple tools you can use to explore more of Matlab&#8217;s internals.  I will only cover basic information, so there are plenty more details left to be filled in by others who are interested.</p><h3 id="Copy-on-write">Brief review of copy-on-write and mxArray</h3><p>Copy-on-write is Matlab&#8217;s mechanism for avoiding unnecessary duplication of data in memory.  To implement this, Matlab needs to keep track internally of which sets of variables are copies of each other.  As described in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f21585.html">MathWorks&#8217;s article</a>, &#8220;<i>the Matlab language works with a single object type: the Matlab array. All Matlab variables (including scalars, vectors, matrices, strings, cell arrays, structures, and objects) are stored as Matlab arrays. In C/C++, the Matlab array is declared to be of type <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/apiref/mxarray.html"><code>mxArray</code></a></i>&#8220;. This means that <code>mxArray</code> defines how Matlab lays out all the information about an array (its Matlab data type, its size, its data, etc.) in memory.  So understanding Matlab&#8217;s internal array representation basically boils down to understanding <code>mxArray</code>.</p><p>Unfortunately, MathWorks also tells us that &#8220;<i><code>mxArray</code> is a C language <a
target='_blank' rel='nofollow' href='http://en.wikipedia.org/wiki/Opaque_pointer'>opaque type</a></i>&#8220;. This means that MathWorks does not expose the organization of <code>mxArray</code> to users (i.e. Matlab or Mex programmers).  Instead, MathWorks defines <code>mxArray</code> internally, and allows users to interact with it only through an API, a set of functions that know how to handle <code>mxArray</code> in their back end.  So, for example, a Mex programmer does not get the dimensions of an <code>mxArray</code> by directly accessing the relevant field in memory.  Instead, the Mex programmer only has a pointer to the <code>mxArray</code>, and passes this pointer into an API function that knows where in memory to find the requested information and then passes the result back to the programmer.</p><p>This is generally a good thing: the API provides an abstraction layer between the programmer and the memory structures so that if MathWorks needs to change the back end organization (to add a new feature for example), we programmers do not need to modify our code; instead MathWorks just updates the API to reflect the new internal organization.  On the other hand, being able to look into the internal structure of <code>mxArray</code> on occasion can help us understand how Matlab works, and can help us write more efficient code if we are careful as in the example of editing arrays in-place.</p><p>So how do we get a glimpse inside <code>mxArray</code>?  The first step is simply to find the region of memory where the <code>mxArray</code> lives: its beginning and end.  Finding where in memory the <code>mxArray</code> begins is pretty easy: it is given by its pointer value.  Here is a simple Mex function that takes a Matlab array as input and prints its memory address:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* printaddr.cpp */</span>
<span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #993333;">void</span> mexFunction<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> nlhs<span style="color: #339933;">,</span> mxArray <span style="color: #339933;">*</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span> nrhs<span style="color: #339933;">,</span> <span style="color: #993333;">const</span> mxArray <span style="color: #339933;">*</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;One input required.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%p<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>This function is nice as it prints the address in a standard hexadecimal format.  The same information can also be received directly in Matlab (i.e., without needing <i><b>printaddr</b></i>), using the undocumented <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/15485#34519"><i><b>format debug</b></i> command</a> (here&#8217;s <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/15988">another reference</a>):</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">format</span> debug
&nbsp;
&gt;&gt; A = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">10</span>
A =
Structure address = 7fc3b8869ae0
m = <span style="color: #33f;">1</span>
n = <span style="color: #33f;">10</span>
pr = 7fc44922c890
<span style="color: #0000FF;">pi</span> = <span style="color: #33f;">0</span>
     <span style="color: #33f;">1</span>     <span style="color: #33f;">2</span>     <span style="color: #33f;">3</span>     <span style="color: #33f;">4</span>     <span style="color: #33f;">5</span>     <span style="color: #33f;">6</span>     <span style="color: #33f;">7</span>     <span style="color: #33f;">8</span>     <span style="color: #33f;">9</span>    <span style="color: #33f;">10</span>
&nbsp;
&gt;&gt; printaddr<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
7fc3b8869ae0</pre></div></div><p>To play with this further from within Matlab however, it's nice to have the address returned to us as a 64-bit unsigned integer; here's a Mex function that does that:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* getaddr.cpp */</span>
<span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #993333;">void</span> mexFunction<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> nlhs<span style="color: #339933;">,</span> mxArray <span style="color: #339933;">*</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span> nrhs<span style="color: #339933;">,</span> <span style="color: #993333;">const</span> mxArray <span style="color: #339933;">*</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;One input required.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   plhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> mxCreateNumericMatrix<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> mxUINT64_CLASS<span style="color: #339933;">,</span> mxREAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> <span style="color: #339933;">*</span>out <span style="color: #339933;">=</span> static_cast<span style="color: #339933;">&lt;</span>unsigned <span style="color: #993333;">long</span> <span style="color: #339933;">*&gt;</span><span style="color: #009900;">&#40;</span>mxGetData<span style="color: #009900;">&#40;</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   out<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span><span style="color: #009900;">&#41;</span> prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>Here's <i><b>getaddr</b></i> in action:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; getaddr<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = 
           <span style="color: #33f;">139870853618400</span>
&nbsp;
<span style="color: #228B22;">% And using pure Matlab:</span>
&gt;&gt; <span style="color: #0000FF;">hex2dec</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'7f36388b5ae0'</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% output of printaddr or format debug</span>
<span style="color: #0000FF;">ans</span> =
           <span style="color: #33f;">139870853618400</span></pre></div></div><p>So now we know where to find our array in memory.  With this information we can already learn a lot.  To make our exploration a little cleaner though, it would be nice to know where the array ends in memory too, in other words we would like to know the size of the <code>mxArray</code>.</p><h3 id="Structure">Finding the structure of mxArray</h3><p>The first thing to understand is that the amount of memory taken by an <code>mxArray</code> does not have anything to do with the dimensions of the array in Matlab.  So a 1x1 Matlab array and a 100x100 Matlab array have the same size <code>mxArray</code> representation in memory.  As you will know if you have experience programming in Mex, this is simply because the Matlab array's data contents are not stored directly within <code>mxArray</code>.  Instead, <code>mxArray</code> only stores a pointer to another memory location where the actual data reside.  This is fine; the internal information we want to poke into is all still in <code>mxArray</code>, and it is easy to get the pointer to the array's data contents using the API functions <i>mxGetData</i> or <i>mxGetPr</i>.</p><p>So we are still left with trying to figure out the size of <code>mxArray</code>.  There are a couple paths forward.  First I want to talk about a historical tool that used to make a lot of this internal information easily available.  This was a function called <i>headerdump</i>, by Peter Boetcher (described <a
target="_blank" rel="nofollow" href="http://www.mit.edu/~pwb/matlab/">here</a> and <a
target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/c241d8821fb90275">here</a>). <i>headerdump</i> was created for exactly the goal we are currently working towards: to understand Matlab's copy-on-write mechanism.  Unfortunately, as Matlab has evolved, newer versions have incrementally broken this useful tool.  So our goal here is to create a replacement.  Still, we can learn a lot from the earlier work.</p><p>One of the things that helped people figure out Matlab's internals in the past is that in older versions of Matlab <code>mxArray</code> is not a completely opaque type.  Even in recent versions up through at least R2010a, if you look into $MATLAB/extern/include/matrix.h you can find a definition of <code>mxArray_tag</code> that looks something like this:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* R2010a */</span>
<span style="color: #993333;">struct</span> mxArray_tag <span style="color: #009900;">&#123;</span>
   <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>reserved<span style="color: #339933;">;</span>
   <span style="color: #993333;">int</span>    reserved1<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
   <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>reserved2<span style="color: #339933;">;</span>
   size_t  number_of_dims<span style="color: #339933;">;</span>
   <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> reserved3<span style="color: #339933;">;</span>
   <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag0  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag1  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag2  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag3  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag4  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag5  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag6  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag7  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag7a <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag8  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag9  <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag10 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag11 <span style="color: #339933;">:</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag12 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>  flag13 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>   flags<span style="color: #339933;">;</span>
   size_t reserved4<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
   <span style="color: #993333;">union</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
           <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>
           <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>pimag_data<span style="color: #339933;">;</span>
           <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>reserved5<span style="color: #339933;">;</span>
           size_t reserved6<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
       <span style="color: #009900;">&#125;</span>   number_array<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>   data<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div><p>This is what you could call murky or obfuscated, but not completely opaque.  The fields mostly have unhelpful names like "reserved", but on the other hand we at least have a sense for what fields there are and their layout.</p><p>A more informative (yet unofficial) definition was <a
target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/b8dbd91953c494fb">provided</a> by James Tursa and Peter Boetcher:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #808080; font-style: italic;">/* Definition of structure mxArray_tag for debugging purposes. Might not be fully correct 
 * for Matlab 2006b or 2007a, but the important things are. Thanks to Peter Boettcher.
 */</span>
<span style="color: #993333;">struct</span> mxArray_tag <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">const</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">;</span>
  mxClassID class_id<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span> vartype<span style="color: #339933;">;</span>
  mxArray    <span style="color: #339933;">*</span>crosslink<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>      number_of_dims<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>      refcount<span style="color: #339933;">;</span>
  <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    scalar_flag <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag1 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag2 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag3 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag4 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag5 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag6 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag7 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    private_data_flag <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag8 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag9 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag10 <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag11 <span style="color: #339933;">:</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag12 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span>    flag13 <span style="color: #339933;">:</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>   flags<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  rowdim<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  coldim<span style="color: #339933;">;</span>
  <span style="color: #993333;">union</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #993333;">double</span>  <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>       <span style="color: #666666; font-style: italic;">// original: void*</span>
      <span style="color: #993333;">double</span>  <span style="color: #339933;">*</span>pimag_data<span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// original: void*</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>irptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>jcptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nelements<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nfields<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>   number_array<span style="color: #339933;">;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      mxArray <span style="color: #339933;">**</span>pdata<span style="color: #339933;">;</span>
      <span style="color: #993333;">char</span>  <span style="color: #339933;">*</span>field_names<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>dummy1<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span>  <span style="color: #339933;">*</span>dummy2<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   dummy3<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nfields<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>   struct_array<span style="color: #339933;">;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>  <span style="color: #808080; font-style: italic;">/*mxGetInfo*/</span>
      <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>field_names<span style="color: #339933;">;</span>
      <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>name<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span> checksum<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>  nelements<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>  reserved<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>  object_array<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>   data<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div><p>For comparison, here is another definition from an earlier version of Matlab.</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* R11 aka Matlab 5.0 (1999) */</span>
<span style="color: #993333;">struct</span> mxArray_tag <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">char</span> name<span style="color: #009900;">&#91;</span>mxMAXNAM<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  class_id<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  vartype<span style="color: #339933;">;</span>
  mxArray <span style="color: #339933;">*</span>crosslink<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  number_of_dims<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  nelements_allocated<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  dataflags<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  rowdim<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span>  coldim<span style="color: #339933;">;</span>
  <span style="color: #993333;">union</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>pdata<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>pimag_data<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>irptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">void</span> <span style="color: #339933;">*</span>jcptr<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   reserved<span style="color: #339933;">;</span>
      <span style="color: #993333;">int</span>   nfields<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>   number_array<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>   data<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div><p>I took this R11 definition from the source code to <i>headerdump</i> (specifically, from <i>mxinternals.h</i>, which also has <code>mxArray_tag</code> definitions for R12 (Matlab 6.0) and R13 (Matlab 6.5)), and you can see that it is much more informative, because many fields have been given useful names thanks to the work of Peter Boetcher and others.  Note also that the definition from this old version of Matlab is quite different from the version from R2010a.</p><p>At this point, if you are running a much earlier version of Matlab like R11 or R13, you can break off from the current article and start playing around with <i>headerdump</i> directly to try to understand Matlab's internals.  For more recent versions of Matlab, we have more work to do.  Getting back to our original goal, if we take the <code>mxArray_tag</code> definition from R2010a and run <i>sizeof</i>, we get an answer for the amount of memory taken up by an <code>mxArray</code> in R2010a: <b>104 bytes</b>.</p><h3 id="Size">Determining the size of mxArray</h3><p>It was nice to derive the size of <code>mxArray</code> from actual MathWorks code, but unfortunately this information is no longer available as of R2011a.  Somewhere between R2010a and R2011a, MathWorks stepped up their efforts to make <code>mxArray</code> completely opaque.  So we should find another way to get the size of <code>mxArray</code> for current and future Matlab versions.</p><p>One ugly trick that works is to create many new arrays quickly and see where their starting points end up in memory:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #0000FF;">num2cell</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">100</span><span style="color: #080;">&#41;</span>';
&gt;&gt; addrs = <span style="color: #0000FF;">sort</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">cellfun</span><span style="color: #080;">&#40;</span>@getaddr, A<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>What we did here is create 100 new arrays, and then get all their memory addresses in sorted order.  Now we can take a look at how far apart these new arrays ended up in memory:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">semilogy</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">diff</span><span style="color: #080;">&#40;</span>addrs<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>The resulting plot will look different each time you run this; it is not really predictable where Matlab will put new arrays into memory.  Here is an example from my system:</p><p><center><div
class="wp-caption aligncenter" style="width: 493px"><img
alt="Plot of memory addresses" src="http://UndocumentedMatlab.com/images/mxArray_memory.png" title="Plot of memory addresses" width="483" height="381" /><p
class="wp-caption-text">Plot of memory addresses</p></div></center></p><p>Your results may look different, and you might have to increase the number of new arrays from 100 to 1000 to get the qualitative result, but the important feature of this plot is that there is a minimum distance between new arrays of about 10<sup>2</sup>.  In fact, if we just go straight for this minimum distance:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">min</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">diff</span><span style="color: #080;">&#40;</span>addrs<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = 
            <span style="color: #33f;">104</span></pre></div></div><p>we find that although <code>mxArray</code> has gone completely opaque from R2010a to R2011a, the full size of <code>mxArray</code> in memory has stayed the same: 104 bytes.</p><h3 id="Dump">Dumping mxArray from memory</h3><p>We now have all the information we need to start looking into Matlab's array representation.  There are many tools available that allow you to browse memory locations or dump memory contents to disk.  For our purposes though, it is nice to be able to do everything from within Matlab.  Therefore I introduce a simple tool that prints memory locations into the Matlab console:</p><div
class="wp_syntax"><div
class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* printmem.cpp */</span>
<span style="color: #339933;">#include &quot;mex.h&quot;</span>
<span style="color: #993333;">void</span> mexFunction<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> nlhs<span style="color: #339933;">,</span> mxArray <span style="color: #339933;">*</span>plhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span> nrhs<span style="color: #339933;">,</span> <span style="color: #993333;">const</span> mxArray <span style="color: #339933;">*</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">||</span> <span style="color: #339933;">!</span>mxIsUint64<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> mxIsEmpty<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;First argument must be a uint64 memory address&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> <span style="color: #339933;">*</span>addr <span style="color: #339933;">=</span> static_cast<span style="color: #339933;">&lt;</span>unsigned <span style="color: #993333;">long</span> <span style="color: #339933;">*&gt;</span><span style="color: #009900;">&#40;</span>mxGetData<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>mem <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> addr<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>nrhs <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">2</span> <span style="color: #339933;">||</span> <span style="color: #339933;">!</span>mxIsDouble<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> mxIsEmpty<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    mexErrMsgTxt<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Second argument must be a double-type integer byte size.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>      
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> nbytes <span style="color: #339933;">=</span> static_cast<span style="color: #339933;">&lt;</span>unsigned int<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>mxGetScalar<span style="color: #009900;">&#40;</span>prhs<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> nbytes<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%.2x &quot;</span><span style="color: #339933;">,</span> mem<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">16</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>Here is how you use it in Matlab:</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #33f;">0</span>;
&gt;&gt; printmem<span style="color: #080;">&#40;</span>getaddr<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>, <span style="color: #33f;">104</span><span style="color: #080;">&#41;</span>
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 <span style="color: #33f;">70</span> fa <span style="color: #33f;">33</span> df 6f 7f 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00</pre></div></div><p>And there you have it: the inner guts of <code>mxArray</code> laid bare.  I have printed each byte as a two character hexadecimal value, as is standard, so there are 16 bytes printed per row.</p><h3 id="">What does it mean?</h3><p>So now we have 104 bytes of Matlab internals to dig into.  We can start playing with this with a few simple examples:</p><pre>
>> A = 0; B = 1;
>> printmem(getaddr(A), 104)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 <span style="background-color:#e6b8af;">c0 b0 27 df 6f 7f</span> 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00

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

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

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

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

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

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

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

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

>> printmem(getaddr(C), 32)
<span style="background-color:#a4c2f4;">10 68 7b 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
</pre><p></p><p>So it turns out that Matlab keeps track of a set of linked variables with a kind of cyclical, doubly-linked list structure; array A is linked to B in the forward direction and is also linked to C in the reverse direction by looping back around, etc.  The cyclical nature of this makes sense, as we need to be able to start from any of A, B, or C and find all the linked arrays.  But it is still not entirely clear why the list needs to be cyclical AND linked in both directions.  In fact, in earlier versions of Matlab this cyclical list was only singly-linked.</p><h3 id="Conclusions">Conclusions</h3><p>Obviously there is a lot more to <code>mxArray</code> and Matlab internals than what we have delved into here.  Still, with this basic introduction I hope to have whet your appetite for understanding more about Matlab internals, and provided some simple tools to help you explore.  I want to reiterate that in general MathWorks's approach of an opaque <code>mxArray</code> type with access abstracted through an API layer is a good policy.  The last thing you would want to do is take the information here and write a bunch of code that relies on the structure of <code>mxArray</code> to work; next time MathWorks needs to add a new feature and change <code>mxArray</code>, all your code will break.  So in general we are all better off playing within the API that MathWorks provides.  And remember: poking into memory can crash your computer, so save your data!</p><p>On the other hand, occasionally there are cases, like in-place editing, where it is useful to push the capabilities of Matlab a little beyond what MathWorks envisioned.  In these cases, having an understanding of Matlab's internals can be critical, for example in understanding how to avoid conflicting with copy-on-write.  Therefore I hope the information presented here will prove useful.  Ideally, someone will be motivated to take this starting point and repair some of the tools like <i>headerdump</i> that made Matlab's internal workings more transparent in the past.  I believe that having more of this information out in the Matlab community is good for the community as a whole.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/' rel='bookmark' title='Matlab mex in-place editing'>Matlab mex in-place editing</a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-properties/' rel='bookmark' title='UDD Properties'>UDD Properties</a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> </channel> </rss>

<!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              b7666
Template:           category
-->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: undocumentedmatlab.com @ 2012-05-18 21:41:10 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/category/presumed-future-risk/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      2.640s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1337402468; expires=Sun, 19-May-2013 04:41:08 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Sat, 19 May 2012 04:41:10 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Sat, 19 May 2012 05:41:10 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               37241e985f2cb8f862d1ac0e5a08aafd
Content-Encoding:   gzip
-->
