<?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; Stock Matlab function</title> <atom:link href="http://undocumentedmatlab.com/blog/category/stock-matlab-function/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>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>Profiling Matlab memory usage</title><link>http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/</link> <comments>http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/#comments</comments> <pubDate>Thu, 01 Mar 2012 00:13:04 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented function]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2768</guid> <description><![CDATA[mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage.<pre> </pre>Related posts:<ol><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/matlabs-internal-memory-representation/' rel='bookmark' title='Matlab&#8217;s internal memory representation'>Matlab&#8217;s internal memory representation</a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/' rel='bookmark' title='Matlab mex in-place editing'>Matlab mex in-place editing</a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/' rel='bookmark' title='Types of undocumented Matlab aspects'>Types of undocumented Matlab aspects</a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Anyone who has had experience with real-life applications knows that Memory usage can have a significant impact on the application&#8217;s usability, in aspects such as performance, interactivity, and even (on some lousy memory-management Operating Systems) crashes/hangs.</p><p>In Matlab releases of the past few years, this has been addressed by expanding the information reported by the built-in <i><b>memory</b></i> function. In addition, an undocumented feature was added to the Matlab Profiler that <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-profiler-options/">enables monitoring</a> memory usage.</p><p><center><div
class="wp-caption aligncenter" style="width: 460px"><br
/> <img
title="Profile report with memory &amp; JIT info" src="http://undocumentedmatlab.com/images/profile2d_450.png" alt="Profile report with memory &amp; JIT info" width="450" /><img
title="Profile report with memory &amp; JIT info" src="http://undocumentedmatlab.com/images/profile2c_450.png" alt="Profile report with memory &amp; JIT info" width="450" /></p><p><img
title="Profile report with memory &amp; JIT info" src="http://undocumentedmatlab.com/images/profile2.png" alt="Profile report with memory &amp; JIT info" width="416" /><br
/><p
class="wp-caption-text">Profile report with memory &amp; JIT info</p></div></center></p><p>In Matlab release R2008a (but not on newer releases) we could also use a nifty parameter of the undocumented <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-feature-function/"><i><b>feature</b></i> function</a>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; feature mtic; a=<span style="color: #0000FF;">ones</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100</span><span style="color: #080;">&#41;</span>; feature mtoc
<span style="color: #0000FF;">ans</span> = 
      TotalAllocated<span style="color: #F0F;">:</span> <span style="color: #33f;">84216</span>
          TotalFreed<span style="color: #F0F;">:</span> <span style="color: #33f;">2584</span>
    LargestAllocated<span style="color: #F0F;">:</span> <span style="color: #33f;">80000</span>
           NumAllocs<span style="color: #F0F;">:</span> <span style="color: #33f;">56</span>
            NumFrees<span style="color: #F0F;">:</span> <span style="color: #33f;">43</span>
                Peak<span style="color: #F0F;">:</span> <span style="color: #33f;">81640</span></pre></div></div><p>As can easily be seen in this example, allocating 100<sup>2</sup> doubles requires 80000 bytes of allocation, plus some 4KB others that were allocated (and 2KB freed) within the function <i><b>ones</b></i>. Running the same code line again gives a very similar result, but now there are 80000 more bytes freed when the matrix <code>a</code> is overwritten:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; feature mtic; a=<span style="color: #0000FF;">ones</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100</span><span style="color: #080;">&#41;</span>; feature mtoc
<span style="color: #0000FF;">ans</span> = 
      TotalAllocated<span style="color: #F0F;">:</span> <span style="color: #33f;">84120</span>
          TotalFreed<span style="color: #F0F;">:</span> <span style="color: #33f;">82760</span>
    LargestAllocated<span style="color: #F0F;">:</span> <span style="color: #33f;">80000</span>
           NumAllocs<span style="color: #F0F;">:</span> <span style="color: #33f;">54</span>
            NumFrees<span style="color: #F0F;">:</span> <span style="color: #33f;">49</span>
                Peak<span style="color: #F0F;">:</span> <span style="color: #33f;">81328</span></pre></div></div><p>This is pretty informative and very handy for debugging memory bottlenecks. Unfortunately, starting in R2008b, features mtic and mtoc are no longer supported <i>&#8220;under the current <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/tech-notes/1100/1106.html">memory manager</a>&#8220;</i>. Sometime around 2010 the mtic and mtoc features were completely removed. Users of R2008b and newer releases therefore need to use the internal structs returned by the <i><b>memory</b></i> function, and/or use the profiler&#8217;s memory-monitoring feature. If you ask me, using mtic/mtoc was much simpler and easier. I for one miss these features.</p><p>In a related matter, if we wish to monitor Java&#8217;s memory used within Matlab, we are in a bind, because there are no built-in tools to help us. there are several JVM switches that can be turned on in the <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-18I2C/"><i>java.opts</i></a> file: -Xrunhprof[:help]|[:option=value,...], -Xprof, -Xrunprof, -XX:+PrintClassHistogram <a
target="_blank" rel="nofollow" href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html">and so on</a>. There are several memory-monitoring (so-called &#8220;heap-walking&#8221;) tools: the standard JDK jconsole, jmap, jhat and jvisualvm (with its useful plugins) provide good basic coverage. MathWorks has <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-3L4JU7/">posted</a> a tutorial on using jconsole with Matlab. There are a number of other third-party tools such as <a
target="_blank" rel="nofollow" href="http://www.khelekore.org/jmp/">JMP</a> (for JVMs 1.5 and earlier) or <a
target="_blank" rel="nofollow" href="http://www.khelekore.org/jmp/tijmp/">TIJMP</a> (for JVM 1.6). Within Matlab, we can use utilities such as <a
target="_blank" rel="nofollow" href="http://www.javamex.com/classmexer/">Classmexer</a> to estimate a particular object&#8217;s size (both shallow and deep referencing), or use <code>java.lang.Runtime.getRuntime()</code>&#8216;s methods (<i>maxMemory(), freeMemory()</i> and <i>totalMemory()</i>) to monitor overall Java memory (<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/296813#797410">sample usage</a>).</p><p>Specifically in R2011b (but in no other release), we can also use a built-in Java memory monitor. Unfortunately, this simple and yet useful memory monitor was removed in R2012a (or maybe it was just moved to another package and I haven&#8217;t found out where&#8230; <i>yet</i>&#8230;):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">com.<span style="">mathworks</span>.<span style="">xwidgets</span>.<span style="">JavaMemoryMonitor</span>.<span style="">invoke</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 230px"><img
alt="Matlab R2011b's Java memory monitor" src="http://UndocumentedMatlab.com/images/Java_Memory_Monitor.png" title="Matlab R2011b's Java memory monitor" width="159" /><p
class="wp-caption-text">Matlab R2011b's Java memory monitor</p></div></center></p><p>As I have already noted quite often, using undocumented Matlab features and functions carries the risk that they will not be supported in some future Matlab release. Today&#8217;s article is a case in point.</p><p><pre> </pre>Related posts:<ol><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/matlabs-internal-memory-representation/' rel='bookmark' title='Matlab&#8217;s internal memory representation'>Matlab&#8217;s internal memory representation</a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/' rel='bookmark' title='Matlab mex in-place editing'>Matlab mex in-place editing</a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/' rel='bookmark' title='Types of undocumented Matlab aspects'>Types of undocumented Matlab aspects</a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Matlab mex in-place editing</title><link>http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/</link> <comments>http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/#comments</comments> <pubDate>Wed, 08 Feb 2012 17:00:25 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Mex]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[Peter Li]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2699</guid> <description><![CDATA[Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/' rel='bookmark' title='Matlab&#8217;s internal memory representation'>Matlab&#8217;s internal memory representation</a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome Matlab Mex power-user <a
target="_blank" rel="nofollow" href="http://absurdlycertain.blogspot.com/">Peter Li</a> to a first in a short series of articles about undocumented aspects of Mex programing</i></p><p>Editing Matlab arrays in-place can be an important technique for optimizing calculations, especially when handling data that use large blocks of memory.  The Matlab language itself has some <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/">limited support for in-place editing</a>, but when we are really concerned with speed we often turn to writing C/C++ extensions using the Mex interface.  Unfortunately, editing arrays in-place from Mex extensions is not officially supported in Matlab, and doing it incorrectly can cause data inconsistencies or can even cause Matlab to crash.  In this article, I will introduce the problem and show a simple solution that exhibit the basic implementation details of Matlab&#8217;s internal copy-on-write mechanism.</p><h3 id="Motivation">Why edit in-place?</h3><p>To demonstrate the techniques in this article, I use the <i>fast_median</i> function, which is part of <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/29453-nthelement">my nth_element package</a> on Matlab&#8217;s File Exchange.  You can download the package and play with the code if you want.  The examples are fairly self-explanatory, so if you do not want to try the code you should be okay just following along.</p><p>Let us try a few function calls to see how editing in-place can save time and memory:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #0000FF;">rand</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
&gt;&gt; <span style="color: #0000FF;">tic</span>; <span style="color: #0000FF;">median</span><span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>    
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">4.122654</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; fast_median<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">1.646448</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; fast_median_ip<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.927898</span> seconds.</pre></div></div><p>If you try running this, be careful not to make A too large; tune the example according to the memory available on your system. In terms of the execution time for the different functions, your mileage may vary depending on factors such as: your system, what Matlab version you are running, and whether your test data is arranged in a single vector or a multicolumn array.</p><p>This example illustrates a few general points: first, <i>fast_median</i> is significantly faster than Matlab&#8217;s <i><b>native</b></i> median function. This is because <i>fast_median</i> uses a more efficient algorithm; see the nth_element page for more details.  Besides being a shameless plug, this demonstrates why we might want to write a Mex function in the first place: rewriting the median function in pure Matlab would be slow, but using C++ we can significantly improve on the status quo.</p><p>The second point is that the in-place version, <i>fast_median_ip</i>, yields an additional speed improvement.  What is the difference?  Let us look behind the scenes; here are the CPU and memory traces from my system monitor after running the above:</p><p><center><div
class="wp-caption alignleft" style="width: 387px"><img
alt="Memory and CPU usage for median() vs. fast_median_ip()" src="http://UndocumentedMatlab.com/images/median_vs_fast_median_ip.png" title="Memory and CPU usage for median() vs. fast_median_ip()" width="377" height="425"/><p
class="wp-caption-text">Memory and CPU usage for <i><b>median</b></i> vs. <i>fast_median_ip</i></p></div></center></p><p>You can see four spikes in CPU use, and some associated changes in memory allocation:</p><p>The first spike in CPU is when we created the test data vector; memory use also steps up at that time.</p><p>The second CPU spike is the largest; that is Matlab&#8217;s median function.  You can see that over that period memory use stepped up again, and then stepped back down; the median function makes a copy of the entire input data, and then throws its copy away when it is finished; this is expensive in terms of time and resources.</p><p>The <i>fast_median</i> function is the next CPU spike; it has a similar step up and down in memory use, but it is much faster.</p><p>Finally, in the case of <i>fast_median_ip</i> we see something different; there is a spike in CPU use, but memory use stays flat; the in-place version is faster and more memory efficient because it does not make a copy of the input data.</p><div
class="" style="width: 100%; overflow: auto;"></div><p>There is another important difference with the in-place version; it modifies its input array.  This can be demonstrated simply:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = randi<span style="color: #080;">&#40;</span><span style="color: #33f;">100</span>, <span style="color: #080;">&#91;</span><span style="color: #33f;">10</span> <span style="color: #33f;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">39</span>    <span style="color: #33f;">42</span>    <span style="color: #33f;">98</span>    <span style="color: #33f;">25</span>    <span style="color: #33f;">64</span>    <span style="color: #33f;">75</span>     <span style="color: #33f;">6</span>    <span style="color: #33f;">56</span>    <span style="color: #33f;">71</span>    <span style="color: #33f;">89</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">median</span><span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">60</span>
&nbsp;
&gt;&gt; fast_median<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">60</span>
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">39</span>    <span style="color: #33f;">42</span>    <span style="color: #33f;">98</span>    <span style="color: #33f;">25</span>    <span style="color: #33f;">64</span>    <span style="color: #33f;">75</span>     <span style="color: #33f;">6</span>    <span style="color: #33f;">56</span>    <span style="color: #33f;">71</span>    <span style="color: #33f;">89</span>
&nbsp;
&gt;&gt; fast_median_ip<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">60</span>
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">39</span>     <span style="color: #33f;">6</span>    <span style="color: #33f;">25</span>    <span style="color: #33f;">42</span>    <span style="color: #33f;">56</span>    <span style="color: #33f;">64</span>    <span style="color: #33f;">75</span>    <span style="color: #33f;">71</span>    <span style="color: #33f;">98</span>    <span style="color: #33f;">89</span></pre></div></div><p>As you can see, all three methods get the same answer, but <i><b>median</b></i> and <i>fast_median</i> do not modify A in the workspace, whereas after running <i>fast_median_ip</i>, input array A has changed.  This is how the in-place method is able to run without using new memory; it operates on the existing array rather than making a copy.</p><h3 id="Pitfalls">Pitfalls with in-place editing</h3><p>Modifying a function&#8217;s input is common in many languages, but in Matlab there are only a few special conditions under which this is officially sanctioned.  This is not necessarily a bad thing; many people feel that modifying input data is bad programming practice and makes code harder to maintain.  But as we have shown, it can be an important capability to have if speed and memory use are critical to an application.</p><p>Given that in-place editing is not officially supported in Matlab Mex extensions, what do we have to do to make it work?  Let us look at the normal, input-copying <i>fast_median</i> function as a starting point:</p><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> mexFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nlhs, mxArray <span style="color: #000040;">*</span>plhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>, <span style="color: #0000ff;">int</span> nrhs, <span style="color: #0000ff;">const</span> mxArray <span style="color: #000040;">*</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   mxArray <span style="color: #000040;">*</span>incopy <span style="color: #000080;">=</span> mxDuplicateArray<span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
   plhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> run_fast_median<span style="color: #008000;">&#40;</span>incopy<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div><p>This is a pretty simple function (I have taken out a few lines of boiler plate input checking to keep things clean).  It relies on helper function <i>run_fast_median</i> to do the actual calculation, so the only real logic here is copying the input array <code>prhs[0]</code>.  Importantly, <i>run_fast_median</i> edits its inputs in-place, so the call to <i>mxDuplicateArray</i> ensures that the Mex function is overall well behaved, i.e. that it does not change its inputs.</p><p>Who wants to be well behaved though?  Can we save time and memory just by taking out the input duplication step?  Let us try it:</p><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> mexFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nlhs, mxArray <span style="color: #000040;">*</span>plhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>, <span style="color: #0000ff;">int</span> nrhs, <span style="color: #0000ff;">const</span> mxArray <span style="color: #000040;">*</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   plhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> run_fast_median<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const_cast</span><span style="color: #000080;">&lt;</span>mxarray <span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>  <span style="color: #666666;">// &lt;/mxarray&gt;</span>
<span style="color: #008000;">&#125;</span></pre></div></div><p>Very bad behavior; note that we cast the original <code>const mxArray*</code> input to a <code>mxArray*</code> so that the compiler will let us mess with it; naughty.</p><p>But does this accomplish edit in-place for <i>fast_median</i>?  Be sure to save any work you have open and then try it:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; mex fast_median_tweaked.<span style="">cpp</span>
&gt;&gt; A = randi<span style="color: #080;">&#40;</span><span style="color: #33f;">100</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">10</span> <span style="color: #33f;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; fast_median_tweaked<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">43</span></pre></div></div><p>Hmm, it looks like this worked fine.  But in fact there are subtle problems:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; A = randi<span style="color: #080;">&#40;</span><span style="color: #33f;">100</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">10</span> <span style="color: #33f;">1</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">65</span>    <span style="color: #33f;">92</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">41</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>     <span style="color: #33f;">2</span>
&gt;&gt; B = A;
&gt;&gt; B'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">65</span>    <span style="color: #33f;">92</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">41</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>     <span style="color: #33f;">2</span>
&nbsp;
&gt;&gt; fast_median_tweaked<span style="color: #080;">&#40;</span>A<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">43</span>
&gt;&gt; A'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">2</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">41</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">65</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>    <span style="color: #33f;">92</span>
&gt;&gt; B'
<span style="color: #0000FF;">ans</span> = <span style="color: #33f;">2</span>     <span style="color: #33f;">2</span>    <span style="color: #33f;">41</span>    <span style="color: #33f;">26</span>    <span style="color: #33f;">14</span>    <span style="color: #33f;">45</span>    <span style="color: #33f;">65</span>    <span style="color: #33f;">85</span>    <span style="color: #33f;">53</span>    <span style="color: #33f;">92</span></pre></div></div><p>Uhoh, spooky; we expected that running <i>fast_median_tweaked</i> would change input A, but somehow it has also changed B, even though B is supposed to be an independent copy.  Not good.  In fact, under some conditions this kind of uncontrolled editing in-place can crash the entire Matlab environment with a segfault.  What is going on?</p><h3 id="COW">Matlab&#8217;s copy-on-write mechanism</h3><p>The answer is that our simple attempt to edit in-place conflicts with Matlab&#8217;s internal copy-on-write mechanism.  Copy-on-write is an optimization built into Matlab to help avoid expensive copying of variables in memory (actually similar to what we are trying to accomplish with edit in-place).  We can see copy-on-write in action with some simple tests:</p><div
class="wp-caption alignright" style="width: 403px"><img
alt="Matlab's Copy-on-Write memory and CPU usage" src="http://UndocumentedMatlab.com/images/copy-on-write.png" title="Matlab's Copy-on-Write memory and CPU usage" width="393" height="466"/><p
class="wp-caption-text">Matlab's Copy-on-Write memory and CPU usage</p></div><div><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Test #1: update, then copy</span>
&gt;&gt; <span style="color: #0000FF;">tic</span>; A = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.588937</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000008</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; B = A; <span style="color: #0000FF;">toc</span>   
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000020</span> seconds.
&nbsp;
<span style="color: #228B22;">% Test #2: copy, then update</span>
&gt;&gt; <span style="color: #0000FF;">clear</span>
&gt;&gt; <span style="color: #0000FF;">tic</span>; A = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.588937</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; B = A; <span style="color: #0000FF;">toc</span>   
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000020</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.678160</span> seconds.</pre></div></div></div><p>In the first set of operations, time and memory are used to create A, but updating A and &#8220;copying&#8221; A into B take no memory and essentially no time.  This may come as a surprise since supposedly we have made an independent copy of A in B; why does creating B take no time or memory when A is clearly a large, expensive block?</p><p>The second set of operations makes things more clear.  In this case, we again create A and then copy it to B; again this operation is fast and cheap.  But assigning into A at this point takes time and consumes a new block of memory, even though we are only assigning into a single index of A.  This is copy-on-write: Matlab tries to save you from copying large blocks of memory unless you need to.  So when you first assign B to equal A, nothing is copied; the variable B is simply set to point to the same memory location already used by A.  Only after you try to change A (or B), does Matlab decide that you really need to have two copies of the large array.</p><p>There are some additional tricks Matlab does with copy-on-write.  Here is another example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">clear</span>
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span> = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.573240</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span> = <span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100000000</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.560369</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; B = A; <span style="color: #0000FF;">toc</span>                     
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000016</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>               
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.690690</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.695758</span> seconds.
&nbsp;
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000011</span> seconds.
&gt;&gt; <span style="color: #0000FF;">tic</span>; A<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> = <span style="color: #33f;">0</span>; <span style="color: #0000FF;">toc</span>
Elapsed time <span style="color: #0000FF;">is</span> <span style="color: #33f;">0.000004</span> seconds.</pre></div></div><p>This shows that for the purposes of copy-on-write, different elements of cell array A are treated independently.  When we assign B equal to A, nothing is copied.  Then when we change any part of A{1}, that whole element must be copied over.  When we subsequently change A{2}, that whole element must also be copied over; it was not copied earlier.  At this point, A and B are truly independent of each other, as both elements have experienced copy-on-write, so further assignments into either A or B are fast and require no additional memory.</p><p>Try playing with some struct arrays and you will find that copy-on-write also works independently for the elements of structs.</p><h3 id="mxUnshareArray">Reconciling edit in-place with copy-on-write: mxUnshareArray</h3><p>Now it is clear why we cannot simply edit arrays in-place from Mex functions; not only is it naughty, it fundamentally conflicts with copy-on-write.  Naively changing an array in-place can inadvertently change other variables that are still waiting for a copy-on-write, as we saw above when <i>fast_median_tweaked</i> inadvertently changed B in the workspace. This is, in the best case, an unmaintainable mess.  Under more aggressive in-place editing, it can cause Matlab to crash with a segfault.</p><p>Luckily, there is a simple solution, although it requires calling internal, undocumented Matlab functions.</p><p>Essentially what we need is a Mex function that can be run on a Matlab array that will do the following:</p><ol><li>Check whether the current array is sharing data with any other arrays that are waiting for copy-on-write.</li><li>If the array is shared, it must be unshared; the underlying memory must be copied and all the relevant pointers need to be fixed so that the array we want to work on is no longer accessible by anyone else.</li><li>If the array is not currently shared, simply proceed; the whole point is to avoid copying memory if we do not need to, so that we can benefit from the efficiencies of edit in-place.</li></ol><p>If you think about it, this is exactly the operation that Matlab needs to run internally when it is deciding whether an assignment operation requires a copy-on-write.  So it should come as no surprise that such a Mex function already exists in the form of a Matlab internal called <i>mxUnshareArray</i>.  Here is how you use it:</p><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">extern</span> <span style="color: #FF0000;">&quot;C&quot;</span> <span style="color: #0000ff;">bool</span> mxUnshareArray<span style="color: #008000;">&#40;</span>mxArray <span style="color: #000040;">*</span>array_ptr, <span style="color: #0000ff;">bool</span> noDeepCopy<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">void</span> mexFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nlhs, mxArray <span style="color: #000040;">*</span>plhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>, <span style="color: #0000ff;">int</span> nrhs, <span style="color: #0000ff;">const</span> mxArray <span style="color: #000040;">*</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   mxUnshareArray<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const_cast</span><span style="color: #000080;">&lt;</span>mxarray <span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>, <span style="color: #0000ff;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>  <span style="color: #666666;">//&lt;/mxarray&gt;</span>
   plhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> run_fast_median<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const_cast</span><span style="color: #000080;">&lt;</span>mxarray <span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>prhs<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>  <span style="color: #666666;">//&lt;/mxarray&gt;</span>
<span style="color: #008000;">&#125;</span></pre></div></div><p>This is the method actually used by <i>fast_median_ip</i> to efficiently edit in-place without risking conflicts with copy-on-write.  Of course, if the array turns out to need to be unshared, then you do not get the benefit of edit in-place because the memory ends up getting copied.  But at least things are safe and you get the in-place benefit as long as the input array is not being shared.</p><h3 id="Extra">Further topics</h3><p>The method shown here should allow you to edit normal Matlab numerical or character arrays in-place from Mex functions safely.  For a Mex function in C rather than C++, omit the &#8220;C&#8221; in the <code>extern</code> declaration and of course you will have to use C-style casting rather than <code>const_cast</code>.  If you need to edit cell or struct arrays in-place, or especially if you need to edit subsections of shared cell or struct arrays safely and efficiently while leaving the rest of the data shared, then you will need a few more tricks.  A good place to get started is <a
target="_blank" rel="nofollow" href="http://www.mk.tu-berlin.de/Members/Benjamin/mex_sharedArrays">this article by Benjamin Schubert</a>.</p><p>Unfortunately, over the last few years Mathworks seems to have decided to make it more difficult for users to access these kinds of internal methods to make our code more efficient.  So be aware of the risk that in some future version of Matlab this method will no longer work in its current form.</p><p>Ultimately much of what is known about <i>mxUnshareArray</i> as well as the internal implementation details of how Matlab keeps track of which arrays are shared goes back to the work of Peter Boettcher, particularly his <a
target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/c241d8821fb90275/">headerdump.c utility</a>.  Unfortunately, it appears that HeaderDump fails with Matlab releases >=R2010a, as Mathworks have changed some of the internal memory formats &#8211; perhaps some smart reader can pick up the work and adapt HeaderDump to the new memory format.</p><p>In a future article, I hope to discuss headerdump.c and its relevance for copy-on-write and edit in-place, and some other related tools for the latest Matlab releases that do not support HeaderDump.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlabs-internal-memory-representation/' rel='bookmark' title='Matlab&#8217;s internal memory representation'>Matlab&#8217;s internal memory representation</a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>MLintFailureFiles or: Why can&#8217;t I save my m-file?!</title><link>http://undocumentedmatlab.com/blog/mlintfailurefiles/</link> <comments>http://undocumentedmatlab.com/blog/mlintfailurefiles/#comments</comments> <pubDate>Thu, 02 Feb 2012 00:14:15 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Editor]]></category> <category><![CDATA[Mlint]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2688</guid> <description><![CDATA[Sometimes Matlab gets into a state where it cannot use a valid m-file. This article explains what can be done.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/recovering-previous-editor-state/' rel='bookmark' title='Recovering previous editor state'>Recovering previous editor state</a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/more-undocumented-timing-features/' rel='bookmark' title='More undocumented timing features'>More undocumented timing features</a> <small>There are several undocumented ways in Matlab to get CPU and clock data...</small></li><li><a
href='http://undocumentedmatlab.com/blog/context-sensitive-help/' rel='bookmark' title='Context-Sensitive Help'>Context-Sensitive Help</a> <small>Matlab has a hidden/unsupported built-in mechanism for easy implementation of context-sensitive help...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-print-setup/' rel='bookmark' title='Customizing print setup'>Customizing print setup</a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>A short while ago, I was working at a client&#8217;s location on some project, when a very strange thing happened: when editing an m-file in the Matlab editor, the mlint process (the one that reports errors and warnings on the right-hand side of the editor) suddenly decided that it has had enough with this specific file. It labeled the entire file as red, meaning that it has errors that prevent it from being run, although as far as we could both see the file was valid and had no syntax errors and actually ran fine.</p><p>Here&#8217;s a screenshot of the message that mlint reported in the editor:</p><p><center><div
class="wp-caption aligncenter" style="width: 542px"><img
alt="erroneous mlint error report" src="http://UndocumentedMatlab.com/images/MLintFailureFiles_mlint_msg.png" title="erroneous mlint error report" width="532" height="44"/><p
class="wp-caption-text">erroneous mlint error report</p></div></center></p><p>Mlint&#8217;s confusion would not have bothered us if it were not for a seemingly-related issue: When we tried to save the file, the Matlab editor would only allow us to save the file under a different name. When we attempted to restart Matlab, the same behavior repeated for this file, and we could not proceed with our actual work, modifying and saving our m-file.</p><p>Not easily intimidated, I tried saving the file under a different name in the editor, then renaming it back outside Matlab. No good, same problem.</p><h3 id="MLintFailureFiles">MLintFailureFiles or: yet another use for <i>prefdir</i></h3><p>The clue that eventually led to the fix was that somehow Matlab remembered the &#8220;faulty&#8221; state of the m-file even after I restarted Matlab. Matlab likes to store persistent cross-session information in a single folder, which is the user&#8217;s <i><b>prefdir</b></i> folder. I have used this to my advantage only a few weeks ago, when I <a
target="_blank" href="http://undocumentedmatlab.com/blog/recovering-previous-editor-state/">explained</a> how to use the stored editor state file that is stored in that folder.</p><p>My hunch was that Matlab might store the mlint&#8217;s &#8220;faulty&#8221; m-file state somewhere in there. I didn&#8217;t have to look very far: one of the files most recently modified had the tell-tale name of <code>MLintFailureFiles</code>. This turns out to be an empty file that contains the full pathname of the &#8220;faulty&#8221; m-files, one file per line.</p><p>The fix turned out to be very easy: simply remove my file from the MLintFailureFiles file (or delete MLintFailureFiles entirely) and restart Matlab. Problem solved – everything back to normal. Resume breathing.</p><h3 id="undocumented">Undocumented? well, not exactly</h3><p>I then went back to the suggestion in the mlint message and true enough I found related information in the documentation, at the bottom of the doc-page for using mlint. This is from R2008a&#8217;s doc page:</p><blockquote><p> <b>About M-Lint and Unexpected MATLAB&reg; Termination</b></p><p>Under some circumstances, when you are editing an M-file, M-Lint can cause the MATLAB session to terminate unexpectedly. The next time you start MATLAB, it displays the following message and disables M-Lint for the M-file that was open in the editor when MATLAB terminated.</p><pre>M-Lint caused your previous MATLAB session to terminate unexpectedly.
Please send this message and file name to The MathWorks.
See "About M-Lint and Unexpected MATLAB Termination" in the MATLAB documentation for details.
</pre><p></p><p>If you want, while waiting for a response from The MathWorks&trade;, you can attempt to reenable M-Lint for the file by following these steps:</p><ol><li>In the Editor, reopen the file that you were editing when MATLAB terminated.</li><li>Remove the lines of code that you believe M-Lint could not handle.</li><li>In a text editor, open the MLintFailureFiles file in your preferences directory. (This is the directory that MATLAB returns when you run prefdir.)</li><li>Save and reopen the M-file.</li></ol></blockquote><p>As you can see, this is not very helpful because it&#8217;s missing the step of actually editing (or deleting) the MLintFailureFiles file.</p><p>Additional documentation of this issue and workaround can be found in two separate Mathworks technical notes: <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-74JVT3/">here</a> and <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-6ZFY8F/">here</a>.</p><p>A Matlab user has even created a <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/29319">utility</a> on the File Exchange that simply deletes this file, basing his work on the first note above.</p><p>The second note indicates that the problem (and workaround) occur in Matlab releases R2008a-R2010b, and indeed the above-mentioned issue (and workaround) can no longer be found in the latest docs (as far as I could see). However, even if this issue (and MLintFailureFiles) may no longer be relevant in the latest Matlab releases, we may still see MLintFailureFiles in our <i><b>prefdir</b></i>, because the <i><b>prefdir</b></i> contents are automatically copied from the previous release whenever we install a newer Matlab release.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/recovering-previous-editor-state/' rel='bookmark' title='Recovering previous editor state'>Recovering previous editor state</a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/more-undocumented-timing-features/' rel='bookmark' title='More undocumented timing features'>More undocumented timing features</a> <small>There are several undocumented ways in Matlab to get CPU and clock data...</small></li><li><a
href='http://undocumentedmatlab.com/blog/context-sensitive-help/' rel='bookmark' title='Context-Sensitive Help'>Context-Sensitive Help</a> <small>Matlab has a hidden/unsupported built-in mechanism for easy implementation of context-sensitive help...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-print-setup/' rel='bookmark' title='Customizing print setup'>Customizing print setup</a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/mlintfailurefiles/feed/</wfw:commentRss> <slash:comments>0</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>Command Window text manipulation</title><link>http://undocumentedmatlab.com/blog/command-window-text-manipulation/</link> <comments>http://undocumentedmatlab.com/blog/command-window-text-manipulation/#comments</comments> <pubDate>Wed, 28 Dec 2011 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[Stock Matlab function]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2645</guid> <description><![CDATA[Special control characters can be used to format text output in Matlab's Command Window.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/cprintf-display-formatted-color-text-in-command-window/' rel='bookmark' title='cprintf &#8211; display formatted color text in the Command Window'>cprintf &#8211; display formatted color text in the Command Window</a> <small>cprintf is a utility that utilized undocumented Matlab desktop functionalities to display color and underline-styled formatted text in the Command Window...</small></li><li><a
href='http://undocumentedmatlab.com/blog/changing-matlab-command-window-colors-part2/' rel='bookmark' title='Changing Matlab&#8217;s Command Window colors &#8211; part 2'>Changing Matlab&#8217;s Command Window colors &#8211; part 2</a> <small>The Matlab Command Window enables a limited degree of inline color customization - this post describes how to use it...</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-v2-setting-command-window-key-bindings/' rel='bookmark' title='EditorMacro v2 &#8211; setting Command Window key-bindings'>EditorMacro v2 &#8211; setting Command Window key-bindings</a> <small>The EditorMacro utility was extended to support built-in Matlab Editor and Command-Window actions and key-bindings. This post describes the changes and the implementation details....</small></li><li><a
href='http://undocumentedmatlab.com/blog/changing-matlab-command-window-colors/' rel='bookmark' title='Changing Matlab&#8217;s Command Window colors'>Changing Matlab&#8217;s Command Window colors</a> <small>Matlab's Command Window foreground and background colors can be modified programmatically, using some of Matlab's undocumented internal Java classes. Here's how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Sometimes the most obscure problems have simple solutions.</p><p>A few days ago, a Matlab user <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/315437">asked</a> whether it is possible to solve the flashing effect whenever he cleared the Command Window. It turns out that this user runs a long process, and wanted to display interim information (progress etc.) in the Command Window. The obvious solution that he employed was to display the data in the Command Window, and then erase the window (using <i><b>clc</b></i>) and rewrite the data periodically.</p><h3 id="Solution">Using control characters</h3><p>Now, there are obviously other ways of doing this, the most obvious being a dedicated GUI window that displays the information and updates periodically. But to solve the user&#8217;s immediate issue, the solution I <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/315437#862184">provided</a> (acting on the 80-20 Pareto principle &#8211; a dedicated GUI window is better but would take longer to set up) was to use control characters to erase old data when displaying new data, rather than clearing the window. Here is the basic pseudo-code that I suggested (slightly modified):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">reverseStr = <span style="color:#A020F0;">''</span>;
<span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> someLargeNumber
&nbsp;
   <span style="color: #228B22;">% Do some computation here...</span>
&nbsp;
   <span style="color: #228B22;">% Display the progress</span>
   percentDone = <span style="color: #33f;">100</span> * idx / someLargeNumber;
   msg = <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Percent done: %3.1f'</span>, percentDone<span style="color: #080;">&#41;</span>
   <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>reverseStr, msg<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
   reverseStr = <span style="color: #0000FF;">repmat</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'\b'</span><span style="color: #080;">&#41;</span>, <span style="color: #33f;">1</span>, <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>msg<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>The idea is to use the backspace control-character (<a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Backspace">BS</a>, or <i><b>sprintf</b></i>(&#8216;\b&#8217;), or <i><b>char</b></i>(8)) repeatedly in order to erase the preceding characters from the Command Window, then print the new data.</p><p>(see related comments by Helge <a
target="_blank" href="http://undocumentedmatlab.com/blog/cprintf-display-formatted-color-text-in-command-window/#comment-56187">here</a>)</p><h3 id="Compatibility">Compatibility aspects</h3><p>Back in the good-ol&#8217;-days, when I was hacking away c-shell scripts, ages ago when I created command-prompt C apps, and aeons ago on Vax (R.I.P.), I would have used the carriage-return control-char (<a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Carriage_return">CR</a>, or <i><b>sprintf</b></i>(&#8216;\r&#8217;), or <i><b>char</b></i>(13)) to completely erase everything up to the beginning of the current line. This would be much simpler than the repeated backspaces (using <i><b>repmat</b></i> in the pseudo-code above). Unfortunately, CRs behave differently in Matlab&#8217;s Command Window, causing \r to jump to the next line (similarly to \n), rather than erase to the beginning of the line. This is probably due to Java&#8217;s JTextArea&#8217;s implementation (on which the Command Window is based), and not due to Matlab itself. In any case, it shows that not all control characters behave the same way on different environments, which is actually not very surprising.</p><p>Another widely-used control character, the bell control-char (<a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Bell_character">BEL</a>, or <i><b>sprintf</b></i>(&#8216;\g&#8217;), or <i><b>char</b></i>(7)) is not accepted at all by Matlab&#8217;s implementation of <i><b>sprintf</b></i> and its variants. Matlab users can always use the <i><b>beep</b></i> function of course, I&#8217;m just pointing this out as another inconsistency between Matlab&#8217;s <i><b>*printf</b></i>() implementation and that of other environments. And don&#8217;t even think of using raw device escape sequences (ah, the good-ol&#8217;-days, long gone now&#8230;).</p><p>Control characters that <i>are</i> accepted in Matlab and behave as expected include: FF (\f), NL (\n) and TAB (\t). These can be used in <i><b>fprintf</b></i> to modify the text spacing. The <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/sprintf.html"><i><b>sprintf</b></i> documentation</a> mentions which of the control characters are accepted, so this is not, strictly speaking, an undocumented aspect. However, note that there is a discrepancy between the list of accepted control chars in the online/<i><b>doc</b></i> page compared to the <i><b>help</b></i> section (\a and \v are mentioned in the former but not in the latter).</p><p>For another type of Command Window text manipulation, namely colors, refer to my <a
target="_blank" href="http://undocumentedmatlab.com/blog/cprintf-display-formatted-color-text-in-command-window/">cprintf utility</a>. For anyone who hasn&#8217;t noticed, I recently updated the utility on the Matlab File Exchange. Due to some internal modifications by MathWorks to the Command Window implementation in R2011b, <i><b>cprintf</b></i> no longer needs to pad color segments with spaces, and separate color segments can now be directly adjacent to each other (in R2011a and earlier, the spaces are unfortunately needed).</p><p>Have you used control characters in an innovative manner in your work? If so, please share your experience in a <a
target="_blank" href="http://UndocumentedMatlab.com/blog/command-window-text-manipulation/#respond">comment</a>.</p><p>Happy New Year everyone!</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/cprintf-display-formatted-color-text-in-command-window/' rel='bookmark' title='cprintf &#8211; display formatted color text in the Command Window'>cprintf &#8211; display formatted color text in the Command Window</a> <small>cprintf is a utility that utilized undocumented Matlab desktop functionalities to display color and underline-styled formatted text in the Command Window...</small></li><li><a
href='http://undocumentedmatlab.com/blog/changing-matlab-command-window-colors-part2/' rel='bookmark' title='Changing Matlab&#8217;s Command Window colors &#8211; part 2'>Changing Matlab&#8217;s Command Window colors &#8211; part 2</a> <small>The Matlab Command Window enables a limited degree of inline color customization - this post describes how to use it...</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-v2-setting-command-window-key-bindings/' rel='bookmark' title='EditorMacro v2 &#8211; setting Command Window key-bindings'>EditorMacro v2 &#8211; setting Command Window key-bindings</a> <small>The EditorMacro utility was extended to support built-in Matlab Editor and Command-Window actions and key-bindings. This post describes the changes and the implementation details....</small></li><li><a
href='http://undocumentedmatlab.com/blog/changing-matlab-command-window-colors/' rel='bookmark' title='Changing Matlab&#8217;s Command Window colors'>Changing Matlab&#8217;s Command Window colors</a> <small>Matlab's Command Window foreground and background colors can be modified programmatically, using some of Matlab's undocumented internal Java classes. Here's how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/command-window-text-manipulation/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Determining axes zoom state</title><link>http://undocumentedmatlab.com/blog/determining-axes-zoom-state/</link> <comments>http://undocumentedmatlab.com/blog/determining-axes-zoom-state/#comments</comments> <pubDate>Thu, 10 Nov 2011 18:45:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Handle graphics]]></category> <category><![CDATA[Hidden property]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2529</guid> <description><![CDATA[The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object.<pre> </pre>Related posts:<ol><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><li><a
href='http://undocumentedmatlab.com/blog/recovering-previous-editor-state/' rel='bookmark' title='Recovering previous editor state'>Recovering previous editor state</a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/axes-looseinset-property/' rel='bookmark' title='Axes LooseInset property'>Axes LooseInset property</a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/setting-axes-tick-labels-format/' rel='bookmark' title='Setting axes tick labels format'>Setting axes tick labels format</a> <small>Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change. ...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>A couple of days ago, a reader of Matlab&#8217;s official Desktop blog <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/2007/12/10/focused-on-zooming/#comment-8204">asked</a> whether it is possible to determine if an axes has been zoomed or not.</p><p>I have encountered this question myself some time ago, when I tried to customize a radar plot: The grid in radar plots does not automatically re-draw when the plot is zoomed, as in regular rectangular plots. Instead, the radial (angle) and circular (range) grid lines are statically painted when the plot is created, and remain fixed when the plot is zoomed or panned. Therefore, if we zoom in on a small-enough plot segment, we will not see any grid lines at all. It would be beneficial to repaint the grid-lines upon every zoom and pan event. I will not dive into the details today, but the important thing for today&#8217;s article is that the algorithm needed to know whether or not the axes is currently zoomed or not.</p><p>The official response is that this information is not readily available. We could of course store the axes limits somewhere and then compare them to the current limits in run-time. This will cause complications if the plotted data (and thereby the axes limits) change automatically during program use, even without any zooming/panning. It is also problematic if the user resets the zoom limits (as Jiro has correctly <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/2007/12/10/focused-on-zooming/#comment-8206">pointed out</a>).</p><p>Today I&#8217;ll highlight another possible solution, that perhaps not many Matlab users are familiar with: Apparently, whenever zooming or panning occur, a hidden <b>ApplicationData</b> object is automatically added to the affected axes, with information about the original axes meta-data: limits, aspect ratio, camera info and view angles. This object is also automatically updated whenever we use <b><i>zoom reset</i></b> to reset the zoom limits.</p><p>So basically, all we have to do in run-time is to compare our current access limits with the stored info: if they are the same (or if the app-data object is missing) then the plot is unzoomed and unpanned; otherwise it is. So simple.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">origInfo = <span style="color: #0000FF;">getappdata</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>, <span style="color:#A020F0;">'matlab_graphics_resetplotview'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>origInfo<span style="color: #080;">&#41;</span>
   isZoomed = <span style="color: #0000FF;">false</span>;
<span style="color: #0000FF;">elseif</span> isequal<span style="color: #080;">&#40;</span><span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'XLim'</span><span style="color: #080;">&#41;</span>, origInfo.<span style="color: #0000FF;">XLim</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">&amp;&amp;</span> <span style="color: #F0F;">...</span>
       <span style="">isequal</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'YLim'</span><span style="color: #080;">&#41;</span>, origInfo.<span style="color: #0000FF;">YLim</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">&amp;&amp;</span> <span style="color: #F0F;">...</span>
       <span style="">isequal</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'ZLim'</span><span style="color: #080;">&#41;</span>, origInfo.<span style="color: #0000FF;">ZLim</span><span style="color: #080;">&#41;</span>
   isZoomed = <span style="color: #0000FF;">false</span>;
<span style="color: #0000FF;">else</span>
   isZoomed = <span style="color: #0000FF;">true</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>This still does not solve the problem of limit changes when the plot data is changed, but it may perhaps be a bit easier to use than manually storing the limits before plotting. (And yes, of course the if-else statement above could be made a one-liner logical construct, but I think this way is more readable).</p><p>Zooming and panning add some additional data to <b>ApplicationData</b>, and also use/modify some other hidden properties of the axes handle (use the <a
target="_blank" href="http://undocumentedmatlab.com/blog/getundoc-get-undocumented-object-properties/"><b><i>getundoc</i></b> function</a> to see them). If you use one of them for any useful purpose, please report your usage in a <a
href="http://undocumentedmatlab.com/blog/determining-axes-zoom-state/#Respond">comment below</a>.</p><p><pre> </pre>Related posts:<ol><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><li><a
href='http://undocumentedmatlab.com/blog/recovering-previous-editor-state/' rel='bookmark' title='Recovering previous editor state'>Recovering previous editor state</a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/axes-looseinset-property/' rel='bookmark' title='Axes LooseInset property'>Axes LooseInset property</a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/setting-axes-tick-labels-format/' rel='bookmark' title='Setting axes tick labels format'>Setting axes tick labels format</a> <small>Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change. ...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/determining-axes-zoom-state/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Multi-line tooltips</title><link>http://undocumentedmatlab.com/blog/multi-line-tooltips/</link> <comments>http://undocumentedmatlab.com/blog/multi-line-tooltips/#comments</comments> <pubDate>Thu, 03 Nov 2011 02:05:36 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[HTML]]></category> <category><![CDATA[Pure Matlab]]></category> <category><![CDATA[Tooltip]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2518</guid> <description><![CDATA[Multi-line tooltips are very easy to set up, once you know your way around a few undocumented hiccups.<pre> </pre>Related posts:<ol><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><li><a
href='http://undocumentedmatlab.com/blog/multi-column-grid-legend/' rel='bookmark' title='Multi-column (grid) legend'>Multi-column (grid) legend</a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</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></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>I often use tooltips in my Matlab GUIs. They are a fantastically intuitive and unobtrusive visual helper for users to understand the GUI. In this blog, I have already posted several articles about how to tweak tooltip contents (<a
target="_blank" href="http://undocumentedmatlab.com/blog/spicing-up-matlab-uicontrol-tooltips/">here</a>, <a
target="_blank" href="http://undocumentedmatlab.com/blog/additional-uicontrol-tooltip-hacks/">here</a>, and <a
target="_blank" href="http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/">here</a>). Today I would like to expand on one of the aspects that were already covered, namely that of multi-line tooltips.</p><h3 id="Basic">Basic multi-line tooltips</h3><p>The basic multi-line tooltip consists of a simple string that includes the newline character. for example:</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>hControl, <span style="color:#A020F0;">'TooltipString'</span>, <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'this is line 1'</span> <span style="color: #33f;">10</span> <span style="color:#A020F0;">'and this is line 2'</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span></pre></div></div><p>Or better (platform independent):</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>hControl, <span style="color:#A020F0;">'TooltipString'</span>, <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'this is line 1\nand this is line 2'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 210px"><img
alt="A simple multi-line tooltip string" src="http://UndocumentedMatlab.com/images/tooltip_multi-line1.png" title="A simple multi-line tooltip string" width="120" /><p
class="wp-caption-text">A simple multi-line tooltip string</p></div></center></p><p>As can be seen, this is very simple to set up. Unfortunately, the font cannot be customized. Which leads us to:</p><h3 id="HTML">HTML-rendered multi-line tooltips</h3><p>Tooltips, like most other Matlab controls, <a
target="_blank" href="http://undocumentedmatlab.com/blog/html-support-in-matlab-uicomponents/">supports HTML rendering</a>. This is a natural corollary of the fact that Java Swing, on which all Matlab controls are based, <a
target="_blank" rel="nofollow" href="http://download.oracle.com/javase/tutorial/uiswing/components/html.html">automatically supports HTML</a>. All we need to do is to add &#8216;<code>&lt;HTML&gt;</code>&#8216; at the very beginning of our tooltip string, and then we can embed HTML tags within the rest of the string:</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>hControl, <span style="color:#A020F0;">'tooltipString'</span>, <span style="color:#A020F0;">'&lt;html&gt;&lt;b&gt;line #1&lt;/b&gt;&lt;br /&gt;&lt;i&gt;&lt;font color=&quot;red&quot;&gt;line#2&lt;/font&gt;&lt;/i&gt;&lt;/html&gt;'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 210px"><img
alt="Multi-line HTML'ed tooltip" src="http://undocumentedmatlab.com/blog/wp-content/uploads/2009/03/html2.png" title="Multi-line HTML'ed tooltip" width="54" /><p
class="wp-caption-text">Multi-line HTML'ed tooltip</p></div></center></p><p>And a more sophisticated example, used within my <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/14225-java-based-data-table">createTable utility</a> on the File Exchange:</p><p><center><div
class="wp-caption aligncenter" style="width: 607px"><img
alt="A more complex multi-line HTML-based tooltip" src="http://UndocumentedMatlab.com/images/table.png" title="A more complex multi-line HTML-based tooltip" width="597" /><p
class="wp-caption-text">A more complex multi-line HTML-based tooltip</p></div></center></p><p>Note that there is no need to close the final HTML tags in the tooltip string, although it&#8217;s not an error to do so (as I have done above).</p><h3 id="Problem">The problem with formatted multi-line tooltip</h3><p>Unfortunately, none of these two methods work when we wish to display formatted multi-line tooltips. For example, suppose that we wish to display struct data in a tooltip:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; myData = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'a'</span>,<span style="color: #0000FF;">pi</span>, <span style="color:#A020F0;">'b'</span>,-<span style="color: #33f;">4</span>, <span style="color:#A020F0;">'very_long_field_name'</span>,<span style="color:#A020F0;">'short txt'</span><span style="color: #080;">&#41;</span>
myData = 
                       a<span style="color: #F0F;">:</span> <span style="color: #33f;">3.14159265358979</span>
                       b<span style="color: #F0F;">:</span> -<span style="color: #33f;">4</span>
    very_long_field_name<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'short txt'</span>
&nbsp;
&gt;&gt; myDataStr = <span style="color: #0000FF;">evalc</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'disp(myData)'</span><span style="color: #080;">&#41;</span>;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hControl, <span style="color:#A020F0;">'TooltipString'</span>, myDataStr<span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 210px"><img
alt="Badly-formatted multi-line tooltip" src="http://UndocumentedMatlab.com/images/tooltip_multi-line2.png" title="Badly-formatted multi-line tooltip" width="200" /><p
class="wp-caption-text">Badly-formatted multi-line tooltip</p></div></center></p><p>If we try to use HTML, the result looks even worse, because if the HTML-renderer detects a newline character embedded in the string, it simply uses the regular (non-HTML) renderer:</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>hControl, <span style="color:#A020F0;">'TooltipString'</span>, <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'&lt;html&gt;'</span> myDataStr <span style="color:#A020F0;">'&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: 210px"><img
alt="Failure to parse a string using HTML" src="http://UndocumentedMatlab.com/images/tooltip_multi-line3.png" title="Failure to parse a string using HTML" width="200" /><p
class="wp-caption-text">Failure to parse a string using HTML</p></div></center></p><p>Even if we fix this by replacing all line-separators with &#8216;<code>&lt;br/&gt;</code>&#8216;, we still get a badly-formatted tooltip, because HTML ignores all white spaces:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; myDataStr2 = <span style="color: #0000FF;">strrep</span><span style="color: #080;">&#40;</span>myDataStr, <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'\n'</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'&lt;br /&gt;'</span><span style="color: #080;">&#41;</span>;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hControl, <span style="color:#A020F0;">'TooltipString'</span>, <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'&lt;html&gt;'</span> myDataStr2 <span style="color:#A020F0;">'&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: 210px"><img
alt="Badly-formatted multi-line tooltip" src="http://UndocumentedMatlab.com/images/tooltip_multi-line4.png" title="Badly-formatted multi-line tooltip" width="200" /><p
class="wp-caption-text">Badly-formatted multi-line tooltip</p></div></center></p><p>(you can see that it&#8217;s HTML-formatted by the fact that the tooltip contents do not have internal margins like in the non-HTML tooltip above)</p><h3 id="Fixed-width">Fixed-width font multi-line tooltips</h3><p>We now recall the HTML <code>&lt;pre&gt;</code> tag, which tells HTML not to ignore white-spaces. In most web browsers, it also defaults to using a fixed-width font. Unfortunately, this is not the case here:</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>hControl, <span style="color:#A020F0;">'TooltipString'</span>, <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'&lt;html&gt;&lt;pre&gt;'</span> myDataStr2<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 250px"><img
alt="Still not quite right..." src="http://UndocumentedMatlab.com/images/tooltip_multi-line5.png" title="Still not quite right..." width="240" /><p
class="wp-caption-text">Still not quite right...</p></div></center></p><p>Which brings us to the final customization of the day, namely explicitly forcing the tooltip to use a fixed-width font:</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>hControl, <span style="color:#A020F0;">'TooltipString'</span>, <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'&lt;html&gt;&lt;pre&gt;&lt;font face=&quot;courier new&quot;&gt;'</span> myDataStr2 <span style="color:#A020F0;">'&lt;/font&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: 330px"><img
alt="Finally - a well-formatted multi-line tooltip" src="http://UndocumentedMatlab.com/images/tooltip_multi-line6.png" title="Finally - a well-formatted multi-line tooltip" width="320" /><p
class="wp-caption-text">Finally - a well-formatted multi-line tooltip</p></div></center></p><p>Even more powerful customizations can be achieved using CSS rather than pure HTML. This will be discussed a future article.</html></pre><p></html></pre><p><pre> </pre>Related posts:<ol><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><li><a
href='http://undocumentedmatlab.com/blog/multi-column-grid-legend/' rel='bookmark' title='Multi-column (grid) legend'>Multi-column (grid) legend</a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</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></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/multi-line-tooltips/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>

<!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              b7666
Template:           category
-->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: undocumentedmatlab.com @ 2012-05-18 21:54:08 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/category/stock-matlab-function/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      2.091s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1337403247; expires=Sun, 19-May-2013 04:54:07 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Sat, 19 May 2012 04:54:08 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Sat, 19 May 2012 05:54:08 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               1e528ffc4054259779f6b2dce2144ca9
Content-Encoding:   gzip
-->
