<?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; Low risk of breaking in future versions</title> <atom:link href="http://undocumentedmatlab.com/blog/category/presumed-future-risk/low-risk-of-breaking-in-future-versions/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 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>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>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>Java stack traces in Matlab</title><link>http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/</link> <comments>http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/#comments</comments> <pubDate>Wed, 07 Mar 2012 18:00:35 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[JMI]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2783</guid> <description><![CDATA[Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>When debugging Java events in Matlab callbacks, it is sometimes useful to check the stack trace of the originating Java code. Matlab&#8217;s built-in <i><b>dbstack</b></i> function only reports the stack-trace of Matlab code, and any prior Java code in the stack trace is not reported. Knowing this information is also extremely important when debugging Java components that are used in Matlab, especially when using the Java-to-Matlab Interface (<a
target="_blank" href="http://undocumentedmatlab.com/tag/JMI/">JMI</a>).</p><p>Let&#8217;s use a specific example to illustrate: Matlab&#8217;s <i><b>uitable</b></i> passes information back and forth between its underlying Java code and Matlab, via the <i><b>arrayviewfunc</b></i> Matlab function (<i>%matlabroot%/toolbox/matlab/codetools/arrayviewfunc.m</i>). If we place a breakpoint in <i><b>arrayviewfunc</b></i> and then update the table&#8217;s data, <i><b>dbstack</b></i> will only report the Matlab stack:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Prepare an empty uitable</span>
&gt;&gt; hTable = uitable<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'ColumnName'</span>,<span style="color: #080;">&#123;</span><span style="color:#A020F0;">'a'</span>,<span style="color:#A020F0;">'b'</span>,<span style="color:#A020F0;">'c'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Place a breakpoint in arrayviewfunc</span>
&gt;&gt; <span style="color: #0000FF;">dbstop</span> in arrayviewfunc at reportValuesCallback
&gt;&gt; <span style="color: #0000FF;">dbstatus</span>
Breakpoint <span style="color: #0000FF;">for</span> arrayviewfunc&gt;reportValuesCallback <span style="color: #0000FF;">is</span> on <span style="color: #0000FF;">line</span> <span style="color: #33f;">588</span>.
&nbsp;
<span style="color: #228B22;">% Update the table data and wait for the breakpoint to trigger</span>
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hTable,<span style="color:#A020F0;">'Data'</span>,<span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Check the Matlab stack trace – no sign of the invoking Java code</span>
K&gt;&gt; <span style="color: #0000FF;">dbstack</span>
&gt; In arrayviewfunc&gt;reportValuesCallback at <span style="color: #33f;">588</span>
  In arrayviewfunc at <span style="color: #33f;">42</span></pre></div></div><p>To see the originating Java stack trace, we can use <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html"><code>java.lang.Thread</code></a>&#8216;s static <i>dumpStack()</i> method, which spills the <a
target="_blank" rel="nofollow" href="http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/">Java stack trace</a> onto the stderr console (will appear in red in Matlab&#8217;s Command Window):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; java.<span style="">lang</span>.<span style="">Thread</span>.<span style="">dumpStack</span>
java.<span style="">lang</span>.<span style="">Exception</span><span style="color: #F0F;">:</span> Stack <span style="color: #0000FF;">trace</span>
   at java.<span style="">lang</span>.<span style="">Thread</span>.<span style="">dumpStack</span><span style="color: #080;">&#40;</span>Unknown Source<span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">SendMatlabMessage</span><span style="color: #080;">&#40;</span>Native Method<span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">219</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabLooper</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>MatlabLooper.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">121</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">Matlab</span>.<span style="">mtFeval</span><span style="color: #080;">&#40;</span>Matlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">1550</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">hg</span>.<span style="">peer</span>.<span style="">ui</span>.<span style="">table</span>.<span style="">DefaultUIStyleTableModel</span>$UITableValueTableModel$1.<span style="">runOnMatlabThread</span><span style="color: #080;">&#40;</span>DefaultUIStyleTableModel.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">467</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabWorker</span>$2.<span style="">run</span><span style="color: #080;">&#40;</span>MatlabWorker.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">79</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">dispatchMTRequests</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">364</span><span style="color: #080;">&#41;</span></pre></div></div><p>To access and possibly parse the originating Java stack trace, we can use the <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/1069066/get-current-stack-trace-in-java">following trick</a>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; st = java.<span style="">lang</span>.<span style="">Thread</span>.<span style="">currentThread</span>.<span style="">getStackTrace</span>;
K&gt;&gt; <span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">2</span> <span style="color: #F0F;">:</span> <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#41;</span>, <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">end</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">SendMatlabMessage</span><span style="color: #080;">&#40;</span>Native Method<span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">219</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabLooper</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>MatlabLooper.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">121</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">Matlab</span>.<span style="">mtFeval</span><span style="color: #080;">&#40;</span>Matlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">1550</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">hg</span>.<span style="">peer</span>.<span style="">ui</span>.<span style="">table</span>.<span style="">DefaultUIStyleTableModel</span>$UITableValueTableModel$1.<span style="">runOnMatlabThread</span><span style="color: #080;">&#40;</span>DefaultUIStyleTableModel.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">467</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabWorker</span>$2.<span style="">run</span><span style="color: #080;">&#40;</span>MatlabWorker.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">79</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">dispatchMTRequests</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">364</span><span style="color: #080;">&#41;</span></pre></div></div><p>Each of the stack trace elements can be inspected, to get specific properties:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>.<span style="">getFileName</span>
<span style="color: #0000FF;">ans</span> =
     <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>		<span style="color: #228B22;">% empty = unknown</span>
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	ClassName = com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>
	FileName = NativeMatlab.<span style="">java</span>
	LineNumber = <span style="color: #080;">&#91;</span>-<span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
	MethodName = SendMatlabMessage
	NativeMethod = on
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">isNativeMethod</span>
<span style="color: #0000FF;">ans</span> =
     <span style="color: #33f;">1</span>		<span style="color: #228B22;">% 1 = true</span>
&nbsp;
K&gt;&gt; <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">getFileName</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% cast java.lang.String to a Matlab char</span>
<span style="color: #0000FF;">ans</span> =
NativeMatlab.<span style="">java</span>
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">getLineNumber</span>
<span style="color: #0000FF;">ans</span> =
    -<span style="color: #33f;">2</span>		<span style="color: #228B22;">% negative = unknown</span>
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">5</span><span style="color: #080;">&#41;</span>.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	ClassName = com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">Matlab</span>
	FileName = Matlab.<span style="">java</span>
	LineNumber = <span style="color: #080;">&#91;</span><span style="color: #33f;">1550</span><span style="color: #080;">&#93;</span>
	MethodName = mtFeval
	NativeMethod = off</pre></div></div><p>This works well in JVM 1.5 (i.e., Matlab 7.04 or R14 SP2) and higher. In older Matlab releases you can use a slight modification:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; t = java.<span style="">lang</span>.<span style="">Throwable</span>; st=t.<span style="">getStackTrace</span>;
K&gt;&gt; <span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#41;</span>, <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">end</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">SendMatlabMessage</span><span style="color: #080;">&#40;</span>Native Method<span style="color: #080;">&#41;</span>
<span style="color: #F0F;">...</span> <span style="color: #080;">&#40;</span>etc.<span style="color: #080;">&#41;</span></pre></div></div><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Using Java Collections in Matlab</title><link>http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/</link> <comments>http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/#comments</comments> <pubDate>Thu, 16 Feb 2012 13:58:49 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2725</guid> <description><![CDATA[Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>In this blog, I posted numerous articles showing how built-in Java functionality can greatly increase Matlab programming productivity and the resulting program power. While not really &#8220;undocumented&#8221; in the true sense (most of the material is actually documented separately in Matlab and Java), in practice, such Java gems are unfortunately often overlooked by Matlab programmers. Many of these tricks are GUI related, but Java has a lot to offer in non-GUI aspects. Today I will show how we can leverage Java&#8217;s extensive Collections classes in non-GUI Matlab programming.</p><h3 id="Collections">Java Collections</h3><p>Java contains a wide variety of predefined data structures (specifically Collections and Maps), which can easily be adapted to fit most programming tasks. It is unfortunate that the Matlab programming language does not contain similar predefined collection types, apart from its basic cell, array and struct elements. Matlab R2008b (7.7) added <i><b>containers.Map</b></i>, which is a much-scaled-down Matlab version of the <code>java.util.Map</code> interface, but is a step in the right direction. Some Matlab programmers prepared their own implementations of data structures, which can be found on the File Exchange.</p><p>Matlab&#8217;s limitation can easily be overcome with Java&#8217;s out-of-the-box set of predefined classes, as described below. Java collections have many advantages over hand-coded Matlab equivalents, in addition to the obvious time saving: Java&#8217;s classes are extensively debugged and performance-tuned, which is especially important when searching large collections. Also, these classes provide a consistent interface, are highly configurable and extendable, enable easy cross-type interoperability and generally give Matlab programmers the full power of Java&#8217;s collections without needing to program the nuts-and-bolts.</p><p>To start using Java collections, readers should first be familiar with them. These classes are part of the core Java language, and are explained in any standard Java programming textbook. The official Java website provides a detailed online <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/collections/">tutorial</a> about these classes, their usage and differences, in addition to a <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/technotes/guides/collections/">detailed reference</a> of these classes.</p><p>Java Collections include interfaces and implementation classes. As of Matlab R2011b, Java interfaces cannot be used directly – only the implementation classes. Of the many Collection classes, the following are perhaps most useful (all classes belong to the <code>java.util</code> package, unless otherwise noted):</p><ul><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html">Set</a>:  an interface that is implemented by classes characterized by their prevention of duplicate elements. Some notable implementation classes: <code>EnumSet</code>, <code>HashSet</code>, <code>LinkedHashSet</code>, <code>TreeSet</code>.</li><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html">List</a>:  an interface that is implemented by classes characterized by ordered elements (a.k.a. sequences), which may be duplicates of each other and accessed based on their exact position within the list. Specially <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/collections/algorithms/">optimized internal algorithms</a> enable sorting, shuffling, reversing, rotating, and other modifications of the list. Some notable implementation classes: <code>Vector</code>, <code>Stack</code>, <code>LinkedList</code>.</li><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html">Queue</a>:  an interface that is implemented by classes designed for holding elements prior to processing, in an ordered list accessible only at one (=<i>head</i>) or two (<i>head</i> and <i>tail</i>) positions. All classes include specialized insertion, extraction and inspection methods. Some notable implementation classes: <code>LinkedList</code>, <code>ArrayDeque</code>, <code>PriorityQueue</code>.</li><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/Map.html">Map</a>:  an interface that is implemented by classes characterized by elements of unique keys paired with associated values. Early Java versions used the <code>java.util.Dictionary</code> abstract superclass, but this was subsequently replaced by the <code>java.util.Map</code> interface class. Maps contain specialized algorithms for fast retrieval based on a supplied key. Some of the notable implementation classes: <code>EnumMap</code>, <code>HashMap</code>, <code>Hashtable</code>, <code>TreeMap</code>, <code>LinkedHashMap</code>.</li></ul><p>As noted, Matlab R2008b (7.7)&#8217;s new <i><b>containers.Map</b></i> class is a scaled-down Matlab version of the <code>java.util.Map</code> interface. It has the added benefit of seamless integration with all Matlab types (unlike Java Collections – see below), as well as the <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/containers.mapclass.html">ability</a> since Matlab 7.10 (R2010a) to specify data types. Serious Matlab implementations requiring key-value maps/dictionaries should still use Java&#8217;s <code>Map</code> classes to gain access to their larger functionality if not performance. Matlab versions earlier than R2008b have no real alternative in any case and must use the Java classes. The reader may also be interested to examine pure-Matlab object-oriented (class-based) <code>Hashtable</code> implementations, available on the File Exchange (<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26778">example1</a>, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28586">example2</a>).</p><p>A potential limitation of using Java Collections is their <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/436852/storing-matlab-structs-in-java-objects">inability</a> to contain non-primitive Matlab types such as structs. To overcome this, either down-convert the types to some simpler type (using the <i><b>struct2cell</b></i> function or programmatically), or create a separate Java object that holds the information and store this object in the Collection.</p><p>Many additional Collection classes offer implementation of specialized needs. For example, <code>java.util.concurrent.LinkedBlockingDeque</code> implements a <code>Queue</code> which is also a <code>LinkedList</code>, is a double-ended queue (<code>Deque</code>) and is blocking (meaning that extraction operations will block until at least one element is extractable).</p><h3 id="Interface">Programming interface</h3><p>All the Java Collections have intentionally similar interfaces, with additional methods specific to each implementation class based on its use and intent. Most Collections implement the following common self-explanatory methods (simplified interface):</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span> size<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">int</span> hashCode<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> isEmpty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> contains<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> element<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> containsAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #003399;">Iterator</span> iterator<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> add<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> element<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> remove<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> element<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> addAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> removeAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> retainAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">void</span> clear<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #003399;">Object</span> clone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> toArray<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #003399;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span></pre></div></div><p>The full list of supported methods in a specific Collection class can, as any other Java object/class, be inspected using Matlab&#8217;s <i><b>methods</b></i> or <i><b>methodsview</b></i> functions (or my utilities, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26947-checkclass"><i><b>checkClass</b></i></a> and <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect"><i><b>uiinspect</b></i></a>):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">methods</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'java.util.Hashtable'</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">Methods</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">class</span> java.<span style="">util</span>.<span style="">Hashtable</span><span style="color: #F0F;">:</span>
Hashtable	containsKey	  equals	<span style="color: #0000FF;">isEmpty</span>   notifyAll	<span style="color: #0000FF;">size</span> 
<span style="color: #0000FF;">clear</span>		containsValue	  <span style="color: #0000FF;">get</span>		keyset    put		toString
clone		elements	  getClass	keys      putAll	values
contains	entrySet	  hashCode	notify    remove	wait</pre></div></div><h3 id="Hashtable">Collections example: Hashtable</h3><p>A detailed Matlab example that utilizes Hashtable (actually, <code>java.util.Properties</code>, which is a subclass of <code>java.util.Hashtable</code>) for a phone-book application is <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f18070.html">detailed</a> in Matlab&#8217;s External Interface/Java section. The following code snippet complements that example by showing some common characteristics of Collections:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; hash = java.<span style="">util</span>.<span style="">Hashtable</span>;
&gt;&gt; hash.<span style="">put</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'key #1'</span>,<span style="color:#A020F0;">'myStr'</span><span style="color: #080;">&#41;</span>;
&gt;&gt; hash.<span style="">put</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'2nd key'</span>,<span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash<span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% same as: hash.toString</span>
<span style="color: #080;">&#123;</span>2nd key=<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@59da0f, key #<span style="color: #33f;">1</span>=myStr<span style="color: #080;">&#125;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">containsKey</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'2nd key'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
     <span style="color: #33f;">1</span>                        <span style="color: #228B22;">% = true</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="color: #0000FF;">size</span><span style="color: #080;">&#41;</span>
     <span style="color: #33f;">2</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'key #2'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% key not found</span>
     <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'key #1'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% key found and value retrieved</span>
myStr
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">entrySet</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">% java.util.Collections$SynchronizedSet object</span>
<span style="color: #080;">&#91;</span>2nd key=<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@192094b, key #<span style="color: #33f;">1</span>=myStr<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; entries = hash.<span style="">entrySet</span>.<span style="">toArray</span>
entries =
java.<span style="">lang</span>.<span style="">Object</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #F0F;">:</span>
    <span style="color: #080;">&#91;</span>java.<span style="">util</span>.<span style="">Hashtable</span>$Entry<span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>java.<span style="">util</span>.<span style="">Hashtable</span>$Entry<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>entries<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
2nd key=<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@192094b
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>entries<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
key #<span style="color: #33f;">1</span>=myStr
&nbsp;
&gt;&gt; hash.<span style="">values</span>  <span style="color: #228B22;">% a java.util.Collections$SynchronizedCollection</span>
<span style="color: #0000FF;">ans</span> =
<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@59da0f, myStr<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; vals = hash.<span style="">values</span>.<span style="">toArray</span>
vals =
java.<span style="">lang</span>.<span style="">Object</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #F0F;">:</span>
    <span style="color: #080;">&#91;</span>3x3 <span style="color: #0000FF;">double</span><span style="color: #080;">&#93;</span>
    <span style="color:#A020F0;">'myStr'</span>
&nbsp;
&gt;&gt; vals<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
     <span style="color: #33f;">8</span>     <span style="color: #33f;">1</span>     <span style="color: #33f;">6</span>
     <span style="color: #33f;">3</span>     <span style="color: #33f;">5</span>     <span style="color: #33f;">7</span>
     <span style="color: #33f;">4</span>     <span style="color: #33f;">9</span>     <span style="color: #33f;">2</span>
&nbsp;
&gt;&gt; vals<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
myStr</pre></div></div><h3 id="Enumerators">Enumerators / Iterators</h3><p>Java Iterators (aka Enumerators), such as those returned by the <i>hash.keys()</i> method, are temporary memory constructs. A common pitfall is to directly chain such constructs. While legal from a syntax viewpoint, this would produce results that are repetitive and probably unintended, as the following code snippet shows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; hash.<span style="">keys</span>
<span style="color: #0000FF;">ans</span> =
java.<span style="">util</span>.<span style="">Hashtable</span>$Enumerator@7b1d52    &lt; = enumerator reference
&gt;&gt; hash.<span style="">keys</span>
<span style="color: #0000FF;">ans</span> =
java.<span style="">util</span>.<span style="">Hashtable</span>$Enumerator@127d1b4   &lt; = new reference object
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">keys</span>.<span style="">nextElement</span><span style="color: #080;">&#41;</span>
2nd key   &lt; = 1st key enumerated in the hash
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">keys</span>.<span style="">nextElement</span><span style="color: #080;">&#41;</span>
2nd key   &lt; = same key returned, because of the new enumeration obj
&nbsp;
&gt;&gt; <span style="color: #228B22;">% Wrong way: causes an endless loop since hash.keys regenerates</span>
&gt;&gt; <span style="color: #228B22;">% ^^^^^^^^^  so hash.keys.hasMoreElements is always true</span>
&gt;&gt; <span style="color: #0000FF;">while</span> hash.<span style="">keys</span>.<span style="">hasMoreElements</span>, doAbc<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">end</span>   <span style="color: #228B22;">% endless loop</span>
&nbsp;
&gt;&gt; <span style="color: #228B22;">% Correct way: store the enumerator in a temporary variable</span>
&gt;&gt; hashKeys = hash.<span style="">keys</span>; 
&gt;&gt; <span style="color: #0000FF;">while</span> hashKeys.<span style="">hasMoreElements</span>,  doAbc<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
&gt;&gt; hash.<span style="">keys</span>.<span style="color: #0000FF;">methods</span>
<span style="color: #0000FF;">Methods</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">class</span> java.<span style="">util</span>.<span style="">Hashtable</span>$Enumerator<span style="color: #F0F;">:</span>
equals            hasNext    nextElement   remove
getClass          hashCode   notify        toString
hasMoreElements   next       notifyAll     wait
&nbsp;
&gt;&gt; <span style="color: #228B22;">% And similarly for ArrayList iterators:</span>
&gt;&gt; jList = java.<span style="">util</span>.<span style="">ArrayList</span>;
&gt;&gt; jList.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">pi</span><span style="color: #080;">&#41;</span>; jList.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'text'</span><span style="color: #080;">&#41;</span>; jList.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>jList<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#91;</span><span style="color: #33f;">3.141592653589793</span>, text, <span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@1c8f959<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; iterator = jList.<span style="">iterator</span>
iterator =
java.<span style="">util</span>.<span style="">AbstractList</span>$Itr@1ab3929
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>iterator.<span style="">next</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hasNext: %d\n'</span>,iterator.<span style="">hasNext</span><span style="color: #080;">&#41;</span>
          <span style="color: #33f;">3.14159265358979</span>
hasNext<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>iterator.<span style="">next</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hasNext: %d\n'</span>,iterator.<span style="">hasNext</span><span style="color: #080;">&#41;</span>
text
hasNext<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>iterator.<span style="">next</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hasNext: %d\n'</span>,iterator.<span style="">hasNext</span><span style="color: #080;">&#41;</span>
     <span style="color: #33f;">8</span>     <span style="color: #33f;">1</span>     <span style="color: #33f;">6</span>
     <span style="color: #33f;">3</span>     <span style="color: #33f;">5</span>     <span style="color: #33f;">7</span>
     <span style="color: #33f;">4</span>     <span style="color: #33f;">9</span>     <span style="color: #33f;">2</span>
hasNext<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span></pre></div></div><p><i><b>More on this topic and other non-GUI Java libraries that can be used in Matlab, can be found in Chapter 2 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">Matlab-Java Programming book</a></b></i>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Using spinners in Matlab GUI</title><link>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/</link> <comments>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/#comments</comments> <pubDate>Wed, 25 Jan 2012 20:00:16 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Internal component]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2679</guid> <description><![CDATA[Spinner controls can easily be added to Matlab GUI. This article explains how.<pre> </pre>Related posts:<ol><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><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/advanced-jide-property-grids/' rel='bookmark' title='Advanced JIDE Property Grids'>Advanced JIDE Property Grids</a> <small>JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks...</small></li><li><a
href='http://undocumentedmatlab.com/blog/blurred-matlab-figure-window/' rel='bookmark' title='Blurred Matlab figure window'>Blurred Matlab figure window</a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>One of the few standard Java Swing controls that does not have any Matlab uicontrol counterpart is <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html"><code>JSpinner</code></a>. <code>JSpinner</code> is basically an editbox with two tiny adjacent up/down buttons. Spinners are similar in functionality to a combo-box (a.k.a. drop-down or pop-up menu), where a user can switch between several pre-selected values. They are often used when the list of possible values is too large to display in a combo-box menu. Like combo-boxes, spinners too can be editable (meaning that the user can type a value in the editbox) or not (the user can only &#8220;spin&#8221; the value using the up/down buttons).</p><p><code>JSpinner</code> uses an internal data model, similarly to <code>JTree</code>, <code>JTable</code> and other complex controls. The default model is <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerNumberModel.html"><code>SpinnerNumberModel</code></a>, which defines a min/max value (unlimited=[] by default) and step-size (1 by default). Additional predefined models are <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerListModel.html"><code>SpinnerListModel</code></a> (which accepts a cell array of possible string values) and <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerDateModel.html"><code>SpinnerDateModel</code></a> (which defines a date range and step unit).</p><p>Here&#8217;s a basic code snippet showing how to display a simple numeric spinner for numbers between 20 and 35, with an initial value of 24 and increments of 1:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jModel = javax.<span style="">swing</span>.<span style="">SpinnerNumberModel</span><span style="color: #080;">&#40;</span><span style="color: #33f;">24</span>,<span style="color: #33f;">20</span>,<span style="color: #33f;">35</span>,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
jSpinner = javax.<span style="">swing</span>.<span style="">JSpinner</span><span style="color: #080;">&#40;</span>jModel<span style="color: #080;">&#41;</span>;
jhSpinner = javacomponent<span style="color: #080;">&#40;</span>jSpinner, <span style="color: #080;">&#91;</span><span style="color: #33f;">10</span>,<span style="color: #33f;">10</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">20</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>The spinner value can be set using the edit-box or by clicking on one of the tiny arrow buttons, or programmatically by setting the <b>Value</b> property. The spinner object also has related read-only properties <b>NextValue</b> and <b>PreviousValue</b>. The spinner&#8217;s model object has the corresponding <b>Value</b> (settable), <b>NextValue</b> (read-only) and <b>PreviousValue</b> (read-only) properties. In addition, the model also has the settable <b>Maximum</b>, <b>Minimum</b> and <b>StepSize</b> properties.</p><p>To attach a data-change callback, set the spinner&#8217;s <b>StateChangedCallback</b> property.</p><p>I have created a small Matlab demo, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26970-spinnerdemo"><i><b>SpinnerDemo</b></i></a>,  which demonstrates usage of <code>JSpinner</code> in Matlab figures. Each of the three predefined models (number, list, and date) is presented, and the spinner values are inter-connected via their callbacks. The Matlab code is modeled after the <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/examples/components/SpinnerDemoProject/src/components/SpinnerDemo.java">Java code</a> that is used to document <code>JSpinner</code> in the official documentation. Readers are welcome to download this demo from the Matlab File Exchange and reuse its source code.</p><p><center><div
class="wp-caption aligncenter" style="width: 225px"><img
alt="Java's SpinnerDemo" src="http://UndocumentedMatlab.com/images/SpinnerDemoJava.png" title="Java's SpinnerDemo" width="215" height="134"/><p
class="wp-caption-text">Java's SpinnerDemo</p></div> &nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 198px"><img
alt="My Matlab SpinnerDemo" src="http://UndocumentedMatlab.com/images/SpinnerDemoMatlab.png" title="My Matlab SpinnerDemo" width="188" height="184"/><p
class="wp-caption-text">My Matlab SpinnerDemo</p></div></center></p><p>As can be seen from the screenshot, <i><b>SpinnerDemo</b></i> also demonstrates how to attach a label to a GUI control with an associated accelerator key (Alt-D in the screenshot example, which sets the focus to the Date control).</p><p>An internal component in Matlab, namely <code>com.mathworks.mwswing.MJSpinner</code>, extends <code>javax.swing.JSpinner</code>, but in this particular case I cannot see any big advantage of using the internal <code>MJSpinner</code> rather than the standard <code>JSpinner</code>. On the contrary, using <code>JSpinner</code> will likely improve forward compatibility &#8211; MathWorks may well change <code>MJSpinner</code> in the future, but it cannot do anything to the standard Swing <code>JSpinner</code>. In other cases, internal Matlab controls do offer significant advantages over the standard Swing controls, but not here it would seem. In any case, the <i><b>SpinnerDemo</b></i> utility uses <code>MJSpinner</code>, but you can safely use <code>JSpinner</code> instead (line #86).</p><p>The internal Matlab controls are discussed in detail in Chapter 5 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">Matlab-Java book</a>, and <code>MJSpinner</code> is specifically discussed in section 5.2.1.</p><p>Another <code>JSpinner</code> derivative is JIDE&#8217;s <code>com.jidesoft.grid.SpinnerCellEditor</code>, which can be used as the cell-editor component in tables. An example of this was shown in the article about <a
target="_blank" href="http://undocumentedmatlab.com/blog/advanced-jide-property-grids/">Advanced JIDE Property Grids</a> (and section 5.7.5 in the book). You may also be interested in the <code>com.jidesoft.combobox.DateSpinnerComboBox</code>, which presents a control that includes both a date-selection combo-box and a spinner (section 5.7.2):</p><p><center><div
class="wp-caption aligncenter" style="width: 310px"><img
alt="A property grid with spinner control" src="http://UndocumentedMatlab.com/images/PropertyGrid_types.png" title="A property grid with spinner control" width="200" height="165" /><p
class="wp-caption-text">A property grid with spinner control</p></div> &nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 289px"><img
alt="JIDE's DateSpinnerComboBox" src="http://UndocumentedMatlab.com/images/DateSpinnerComboBox.png" title="JIDE's DateSpinnerComboBox" width="279" height="228" /><p
class="wp-caption-text">JIDE's DateSpinnerComboBox</p></div></center></p><p><pre> </pre>Related posts:<ol><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><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/advanced-jide-property-grids/' rel='bookmark' title='Advanced JIDE Property Grids'>Advanced JIDE Property Grids</a> <small>JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks...</small></li><li><a
href='http://undocumentedmatlab.com/blog/blurred-matlab-figure-window/' rel='bookmark' title='Blurred Matlab figure window'>Blurred Matlab figure window</a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Matlab-Java memory leaks, performance</title><link>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/</link> <comments>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/#comments</comments> <pubDate>Fri, 20 Jan 2012 00:56:10 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Semi-documented feature]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Performance]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2665</guid> <description><![CDATA[Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance.<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/preallocation-performance/' rel='bookmark' title='Preallocation performance'>Preallocation performance</a> <small>Preallocation is a standard Matlab speedup technique. Still, it has several undocumented aspects. ...</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-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>There are several ways of retrieving information from a Java object into Matlab. On the face of it, all these methods look similar. But it turns out that there are important differences between them in terms of memory leakage and performance.</p><h3 id="Problem">The problem: &#8220;Matlab crashes&#8221; &#8211; now go figure&#8230;</h3><p>A client of one of my Matlab programs recently complained that Matlab crashes after several hours of extensive use of the program. The problem looked like something that is memory related (messages such as Matlab&#8217;s out-of-memory error or Java&#8217;s heap-space error). Apparently this happens even on 64-bit systems having lots of memory, where memory should never be a problem.</p><p>Well, we know that this is only in theory, but in practice Matlab&#8217;s internal memory management has problems that occasionally lead to such crashes. This is one of the reasons, by the way, that recent Matlab releases have added the preference option of increasing the default Java heap space (the previous way to do this was <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-18I2C/">a bit complex</a>). Still, even with a high Java heap space setting and lots of RAM, Matlab crashed after using my program for several hours.</p><p>Not pleasant at all, even a bit of an embarrassment for me. I&#8217;m used to crashing Matlab, but only as a result of my playing around with the internals &#8211; I would hate it to happen to my clients.</p><h3 id="Finding">Finding the leak</h3><p>While we can do little with Matlab&#8217;s internal memory manager, I started searching for the exact location of the memory leak and then to find a way to overcome it. I&#8217;ll save readers the description about the grueling task of finding out exactly where the memory leak occurred in a program that has thousands of lines of code and where events get fired asynchronously on a constant basis. <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-profiler-options/">Matlab Profiler&#8217;s undocumented memory profiling option</a> helped me quite a bit, as well as lots of intuition and trial-and-error. Detecting memory leak is never easy, and I consider myself somewhat lucky this time to have both detected the leak source and a workaround.</p><p>It turned out that the leakage happens in a callback that gets invoked multiple times per second by a Java object (see related articles <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/">here</a> and <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/">here</a>). Each time the Matlab callback function is invoked, it reads the event information from the supplied Java event-data (the callback&#8217;s second input parameter). Apparently, about 1KB of memory gets leaked whenever this event-data is being read. This may appear a very small leak, but multiply this by some 50-100K callback invocations per hour and you get a leakage of 50-100MB/hour. Not a small leak at all; more of a flood you could say&#8230;</p><h3 id="get">Using <i><b>get</b>()</i></h3><p>The leakage culprit turned out to be the following code snippet:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 160 uSecs per call, with memory leak</span>
eventData  = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hEventData,<span style="color: #080;">&#123;</span><span style="color:#A020F0;">'EventName'</span>,<span style="color:#A020F0;">'ParamNames'</span>,<span style="color:#A020F0;">'EventData'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
eventName  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>;
paramNames = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span>;
paramData  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">3</span><span style="color: #080;">&#125;</span>.<span style="color: #0000FF;">cell</span>;</pre></div></div><p>In this innocent-looking code, <code>hEventData</code> is a Java object that contains the <b>EventName, ParamNames, EventData</b> properties: <b>EventName</b> is a Java <code>String</code>, that is automatically converted by Matlab&#8217;s <i><b>get</b>()</i> function into a Matlab string (<i><b>char</b></i> array); <b>ParamNames</b> is a Java array of <code>String</code>s, that gets automatically converted into a Matlab cell-array of string; and <b>EventData</b> is a Java array of <code>Object</code>s that needs to be converted into a Matlab cell array using the built-in <i><b>cell</b></i> function, as <a
target="_blank" href="http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/">described</a> in one of my recent articles.</p><p>The code is indeed innocent, works really well and is actually extremely fast: each invocation takes of this code segment takes less than 0.2 millisecs. Unfortunately, because of the memory leak I needed to find a better alternative.</p><h3 id="handle">Using <i><b>handle</b>()</i></h3><p>The first idea was to use the built-in <i><b>handle</b>()</i> function, under the assumption that it would solve the memory leak, as <a
target="_blank" rel="nofollow" href="http://mathforum.org/kb/message.jspa?messageID=5950839">reported here</a>. In fact, MathWorks specifically advises to use <i><b>handle</b>()</i> rather than to work with &#8220;naked&#8221; Java objects, when <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/#memory_leak">setting Java object callbacks</a>. The official documentation of the <i><b>set</b></i> function <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/set.html#f67-433534">says</a>:</p><blockquote><p>Do not use the set function on Java objects as it will cause a memory leak.</p></blockquote><p>It stands to reason then that a similar memory leak happens with <i><b>get</b></i> and that a similar use of <i><b>handle</b></i> would solve this problem:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 300 uSecs per call, with memory leak</span>
s = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
eventName  = s.<span style="">EventName</span>;
paramNames = s.<span style="">ParamNames</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">EventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Unfortunately, this variant, although working correctly, still leaks memory, and also performs almost twice as worse than the original version, taking some 0.3 milliseconds to execute per invocation. Looks like this is a dead end.</p><h3 id="accessor">Using Java accessor methods</h3><p>The next attempt was to use the Java object&#8217;s internal accessor methods for the requested properties. These are <code>public</code> methods of the form <i>getXXX(), isXXX(), setXXX()</i> that enable Matlab to treat XXX as a property by its <i><b>get</b></i> and <i><b>set</b></i> functions. In our case, we need to use the getter methods, as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 380 uSecs per call, no memory leak</span>
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getParamNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Here, the method <i>getEventName()</i> returns a Java <code>String</code>, that we convert into a Matlab string using the <i><b>char</b></i> function. In our previous two variants, the <i><b>get</b></i> function did this conversion for us automatically, but when we use the Java method directly we need to convert the results ourselves. Similarly, when we call <i>getParamNames()</i>, we need to use the <i><b>cell</b></i> function to convert the Java <code>String[]</code> array into a Matlab cell array.</p><p>This version at last doesn&#8217;t leak any memory. Unfortunately, it has an even worse performance: each invocation takes almost 0.4 milliseconds. The difference may seem insignificant. However, recall that this callback gets called dozens of times each second, so the total adds up quickly. It would be nice if there were a faster alternative that does not leak any memory.</p><h3 id="struct">Using <i><b>struct</b>()</i></h3><p>Luckily, I found just such an alternative. At 0.24 millisecs per invocation, it is almost as fast as the leaky best-performance original <i><b>get</b></i> version. Best of all, it leaks no memory, at least none that I could detect.</p><p>The mechanism relies on the little-known fact that public fields of Java objects can be retrieved in Matlab using the built-in <i><b>struct</b></i> function. For example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="color: #0000FF;">Rectangle</span><span style="color: #080;">&#41;</span>
fields = 
             x<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
             y<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
         width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
        height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
      OUT_LEFT<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
       OUT_TOP<span style="color: #F0F;">:</span> <span style="color: #33f;">2</span>
     OUT_RIGHT<span style="color: #F0F;">:</span> <span style="color: #33f;">4</span>
    OUT_BOTTOM<span style="color: #F0F;">:</span> <span style="color: #33f;">8</span>
&nbsp;
&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="">Dimension</span><span style="color: #080;">&#41;</span>
fields = 
     width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
    height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span></pre></div></div><p>Note that this useful mechanism is not mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f4873.html#f46643">the main documentation page for accessing Java object fields</a>, although it is indeed mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f6671.html#f61403">another doc-page</a> &#8211; I guess this is a documentation oversight.</p><p>In any case, I converted my Java object to use public (rather than private) fields, so that I could use this <i><b>struct</b></i> mechanism (Matlab can only access public fields). Yes I know that using private fields is a better programming practice and all that (I&#8217;ve programmed OOP for some 15 years&#8230;), but sometimes we need to do ugly things in the interest of performance. The latest version now looks like this:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 240 uSecs per call, no memory leak</span>
s = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span>;
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>s.<span style="">eventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">paramNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">eventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This solved the memory leakage issue for my client. I felt fortunate that I was not only able to detect Matlab&#8217;s memory leak but also find a working workaround without sacrificing performance or functionality.</p><p>In this particular case, I was lucky to have full control over my Java object, to be able to convert its fields to become public. Unfortunately, we do not always have similar control over the object that we use, because they were coded by a third party.</p><p>By the way, Matlab itself uses this <i><b>struct</b></i> mechanism in its code-base. For example, Matlab timers are implemented using Java objects (<code>com.mathworks.timer.TimerTask</code>). The timer callback in Matlab code converts the Java timer event data into a Matlab struct using the <i><b>struct</b></i> function, in <i>%matlabroot%/toolbox/matlab/iofun/@timer/timercb.m</i>. The users of the timer callbacks then get passed a simple Matlab EventData struct without ever knowing that the original data came from a Java object.</p><p>As an interesting corollary, this same <i><b>struct</b></i> mechanism can be used to detect internal properties of Matlab class objects. For example, in the timers again, we can get the underlying timer&#8217;s Java object as follows (note the highlighted warning, which I find a bit ironic given the context):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; timerObj = timerfind
&nbsp;
   Timer Object<span style="color: #F0F;">:</span> timer-<span style="color: #33f;">1</span>
&nbsp;
   Timer Settings
      ExecutionMode<span style="color: #F0F;">:</span> singleShot
             Period<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
           BusyMode<span style="color: #F0F;">:</span> drop
            Running<span style="color: #F0F;">:</span> off
&nbsp;
   Callbacks
           TimerFcn<span style="color: #F0F;">:</span> @myTimerFcn
           ErrorFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
           StartFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
            StopFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
&nbsp;
&gt;&gt; timerFields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>timerObj<span style="color: #080;">&#41;</span>
<span style="display:block;background-color: #ffc;"><span style="color: #0000FF;">Warning</span><span style="color: #F0F;">:</span> Calling <span style="color: #0000FF;">STRUCT</span> on an object prevents the object from hiding its implementation details and should thus be avoided.</span><span style="display:block;background-color: #ffc;"><span style="">Use</span> <span style="color: #0000FF;">DISP</span> or DISPLAY to see the visible public details of an object. <span style="">See</span> <span style="color:#A020F0;">'help struct'</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">more</span> information.</span><span style="display:block;background-color: #ffc;"><span style="color: #080;">&#40;</span><span style="color: #0000FF;">Type</span> &quot;warning off MATLAB<span style="color: #F0F;">:</span>structOnObject&quot; to suppress this <span style="color: #0000FF;">warning</span>.<span style="color: #080;">&#41;</span></span>timerFields = 
         ud<span style="color: #F0F;">:</span> <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>
    jobject<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 javahandle.<span style="">com</span>.<span style="">mathworks</span>.<span style="">timer</span>.<span style="">TimerTask</span><span style="color: #080;">&#93;</span></pre></div></div><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/preallocation-performance/' rel='bookmark' title='Preallocation performance'>Preallocation performance</a> <small>Preallocation is a standard Matlab speedup technique. Still, it has several undocumented aspects. ...</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-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/matlab-java-memory-leaks-performance/feed/</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Recovering previous editor state</title><link>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/</link> <comments>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/#comments</comments> <pubDate>Wed, 11 Jan 2012 18:00:49 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Desktop]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Editor]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2656</guid> <description><![CDATA[Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/non-textual-editor-actions/' rel='bookmark' title='Non-textual editor actions'>Non-textual editor actions</a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-assign-a-keyboard-macro-in-the-matlab-editor/' rel='bookmark' title='EditorMacro &#8211; assign a keyboard macro in the Matlab editor'>EditorMacro &#8211; assign a keyboard macro in the Matlab editor</a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/tri-state-checkbox/' rel='bookmark' title='Tri-state checkbox'>Tri-state checkbox</a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><span
class="alignright"><img
title="Editor with multiple loaded documents" src="http://undocumentedmatlab.com/images/editor.png" alt="Editor with multiple loaded documents" width="300" height="380"/></span> I find it very useful to use the Matlab editor&#8217;s ability to load multiple files to help me remember which files I still need to work on. I typically have a few dozen files loaded in the editor. I guess you could say that the editor&#8217;s list of files is a simple reflection of my open tasks. It would be extremely inconvenient if I ever lost this list.</p><p>Which is, unfortunately, exactly what happened to me yesterday.</p><p>I was about to close a figure window and accidentally closed the editor window that was behind it.</p><p>I was now in quite a jam: reopening the editor would not load all my files, but start with a blank (empty) editor. The Matlab editor, unlike modern browsers, does not have a &#8216;reopen last session&#8217; option, and using the most-recently-used (MRU) files list would at best return the latest 9 files (the default Matlab preference is to have an MRU depth of only 4 files, but this is one of the very first things that I change whenever I install Matlab, along with a few other very questionable [IMHO] default preferences).</p><p>Luckily for me, there is an escape hatch: Matlab stores its Desktop windows state in a file called <i>MATLABDesktop.xml</i> that is located in the user&#8217;s <i><b>prefdir</b></i> folder. This file includes information about the position and state (docked/undocked etc.) of every Desktop window. Since the editor files are considered Desktop documents (you can see them under the Desktop&#8217;s main menu&#8217;s Window menu), they are also included in this file. When I closed the Editor, these documents were simply removed from the <i>MATLABDesktop.xml</i> file.</p><p>It turns out that Matlab automatically stores a backup version of this file in another file called <i>MATLABDesktop.xml.prev</i>, in the same <i><b>prefdir</b></i> folder. We can inspect the folder using our system&#8217;s file browser. For example, on Windows we could use:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">winopen<span style="color: #080;">&#40;</span>prefdir<span style="color: #080;">&#41;</span></pre></div></div><p>So before doing anything else, I closed Matlab (I actually crashed it to prevent any cleanup tasks to accidentally erase this backup file, but that turned out to be an unnecessary precaution), deleted the latest <i>MATLABDesktop.xml</i> file, replaced it with a copy of the <i>MATLABDesktop.xml.prev</i> file (which I renamed <i>MATLABDesktop.xml</i>), and only then did I restart Matlab.</p><p>Problem solved &#8211; everything back to normal. Resume breathing. Once again I have my never-ending virtual task list in front of me as I write this.</p><p>Lessons learned:</p><ol><li>don&#8217;t be too quick on the close button trigger</li><li>always keep a relatively recent backup copy of your important config files (BTW, I use the same advice with my FireFox browser, where I normally have dozens of open tabs &#8211; I keep a backup copy of the sessionstore.js file)</li><li>if you do get into a jam, don&#8217;t do anything hasty that might make recovery impossible. Calm down, look around, and maybe you&#8217;ll find an automatic backup somewhere</li></ol><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/non-textual-editor-actions/' rel='bookmark' title='Non-textual editor actions'>Non-textual editor actions</a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-assign-a-keyboard-macro-in-the-matlab-editor/' rel='bookmark' title='EditorMacro &#8211; assign a keyboard macro in the Matlab editor'>EditorMacro &#8211; assign a keyboard macro in the Matlab editor</a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/tri-state-checkbox/' rel='bookmark' title='Tri-state checkbox'>Tri-state checkbox</a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> </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:45:46 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/category/presumed-future-risk/low-risk-of-breaking-in-future-versions/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      2.033s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1337402744; expires=Sun, 19-May-2013 04:45:44 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Sat, 19 May 2012 04:45:46 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Sat, 19 May 2012 05:45:46 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               a87926c0b773096caa0a0459a850714e
Content-Encoding:   gzip
-->
