<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
><channel><title>Undocumented Matlab &#187; Presumed future risk</title> <atom:link href="http://undocumentedmatlab.com/blog/category/presumed-future-risk/feed/" rel="self" type="application/rss+xml" /><link>http://undocumentedmatlab.com</link> <description>Charting Matlab's unsupported hidden underbelly</description> <lastBuildDate>Wed, 08 Feb 2012 18:40:25 +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>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[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><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/undocumented-profiler-options/' rel='bookmark' title='Undocumented profiler options'>Undocumented profiler options</a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</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><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li></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/undocumented-profiler-options/' rel='bookmark' title='Undocumented profiler options'>Undocumented profiler options</a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</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><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-mex-in-place-editing/feed/</wfw:commentRss> <slash:comments>0</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/undocumented-scatter-plot-behavior/' rel='bookmark' title='Undocumented scatter plot behavior'>Undocumented scatter plot behavior</a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-events-and-listeners/' rel='bookmark' title='UDD Events and Listeners'>UDD Events and Listeners</a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li></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="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/undocumented-scatter-plot-behavior/' rel='bookmark' title='Undocumented scatter plot behavior'>Undocumented scatter plot behavior</a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-events-and-listeners/' rel='bookmark' title='UDD Events and Listeners'>UDD Events and Listeners</a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/mlintfailurefiles/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Using spinners in Matlab GUI</title><link>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/</link> <comments>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/#comments</comments> <pubDate>Wed, 25 Jan 2012 20:00:16 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Internal component]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2679</guid> <description><![CDATA[Spinner controls can easily be added to Matlab GUI. This article explains how.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/advanced-jide-property-grids/' rel='bookmark' title='Advanced JIDE Property Grids'>Advanced JIDE Property Grids</a> <small>JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks...</small></li><li><a
href='http://undocumentedmatlab.com/blog/blurred-matlab-figure-window/' rel='bookmark' title='Blurred Matlab figure window'>Blurred Matlab figure window</a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>One of the few standard Java Swing controls that does not have any Matlab uicontrol counterpart is <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html"><code>JSpinner</code></a>. <code>JSpinner</code> is basically an editbox with two tiny adjacent up/down buttons. Spinners are similar in functionality to a combo-box (a.k.a. drop-down or pop-up menu), where a user can switch between several pre-selected values. They are often used when the list of possible values is too large to display in a combo-box menu. Like combo-boxes, spinners too can be editable (meaning that the user can type a value in the editbox) or not (the user can only &#8220;spin&#8221; the value using the up/down buttons).</p><p><code>JSpinner</code> uses an internal data model, similarly to <code>JTree</code>, <code>JTable</code> and other complex controls. The default model is <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerNumberModel.html"><code>SpinnerNumberModel</code></a>, which defines a min/max value (unlimited=[] by default) and step-size (1 by default). Additional predefined models are <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerListModel.html"><code>SpinnerListModel</code></a> (which accepts a cell array of possible string values) and <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerDateModel.html"><code>SpinnerDateModel</code></a> (which defines a date range and step unit).</p><p>Here&#8217;s a basic code snippet showing how to display a simple numeric spinner for numbers between 20 and 35, with an initial value of 24 and increments of 1:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jModel = javax.<span style="">swing</span>.<span style="">SpinnerNumberModel</span><span style="color: #080;">&#40;</span><span style="color: #33f;">24</span>,<span style="color: #33f;">20</span>,<span style="color: #33f;">35</span>,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
jSpinner = javax.<span style="">swing</span>.<span style="">JSpinner</span><span style="color: #080;">&#40;</span>jModel<span style="color: #080;">&#41;</span>;
jhSpinner = javacomponent<span style="color: #080;">&#40;</span>jSpinner, <span style="color: #080;">&#91;</span><span style="color: #33f;">10</span>,<span style="color: #33f;">10</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">20</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>The spinner value can be set using the edit-box or by clicking on one of the tiny arrow buttons, or programmatically by setting the <b>Value</b> property. The spinner object also has related read-only properties <b>NextValue</b> and <b>PreviousValue</b>. The spinner&#8217;s model object has the corresponding <b>Value</b> (settable), <b>NextValue</b> (read-only) and <b>PreviousValue</b> (read-only) properties. In addition, the model also has the settable <b>Maximum</b>, <b>Minimum</b> and <b>StepSize</b> properties.</p><p>To attach a data-change callback, set the spinner&#8217;s <b>StateChangedCallback</b> property.</p><p>I have created a small Matlab demo, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26970-spinnerdemo"><i><b>SpinnerDemo</b></i></a>,  which demonstrates usage of <code>JSpinner</code> in Matlab figures. Each of the three predefined models (number, list, and date) is presented, and the spinner values are inter-connected via their callbacks. The Matlab code is modeled after the <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/examples/components/SpinnerDemoProject/src/components/SpinnerDemo.java">Java code</a> that is used to document <code>JSpinner</code> in the official documentation. Readers are welcome to download this demo from the Matlab File Exchange and reuse its source code.</p><p><center><div
class="wp-caption aligncenter" style="width: 225px"><img
alt="Java's SpinnerDemo" src="http://UndocumentedMatlab.com/images/SpinnerDemoJava.png" title="Java's SpinnerDemo" width="215" height="134"/><p
class="wp-caption-text">Java's SpinnerDemo</p></div> &nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 198px"><img
alt="My Matlab SpinnerDemo" src="http://UndocumentedMatlab.com/images/SpinnerDemoMatlab.png" title="My Matlab SpinnerDemo" width="188" height="184"/><p
class="wp-caption-text">My Matlab SpinnerDemo</p></div></center></p><p>As can be seen from the screenshot, <i><b>SpinnerDemo</b></i> also demonstrates how to attach a label to a GUI control with an associated accelerator key (Alt-D in the screenshot example, which sets the focus to the Date control).</p><p>An internal component in Matlab, namely <code>com.mathworks.mwswing.MJSpinner</code>, extends <code>javax.swing.JSpinner</code>, but in this particular case I cannot see any big advantage of using the internal <code>MJSpinner</code> rather than the standard <code>JSpinner</code>. On the contrary, using <code>JSpinner</code> will likely improve forward compatibility &#8211; MathWorks may well change <code>MJSpinner</code> in the future, but it cannot do anything to the standard Swing <code>JSpinner</code>. In other cases, internal Matlab controls do offer significant advantages over the standard Swing controls, but not here it would seem. In any case, the <i><b>SpinnerDemo</b></i> utility uses <code>MJSpinner</code>, but you can safely use <code>JSpinner</code> instead (line #86).</p><p>The internal Matlab controls are discussed in detail in Chapter 5 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">Matlab-Java book</a>, and <code>MJSpinner</code> is specifically discussed in section 5.2.1.</p><p>Another <code>JSpinner</code> derivative is JIDE&#8217;s <code>com.jidesoft.grid.SpinnerCellEditor</code>, which can be used as the cell-editor component in tables. An example of this was shown in the article about <a
target="_blank" href="http://undocumentedmatlab.com/blog/advanced-jide-property-grids/">Advanced JIDE Property Grids</a> (and section 5.7.5 in the book). You may also be interested in the <code>com.jidesoft.combobox.DateSpinnerComboBox</code>, which presents a control that includes both a date-selection combo-box and a spinner (section 5.7.2):</p><p><center><div
class="wp-caption aligncenter" style="width: 310px"><img
alt="A property grid with spinner control" src="http://UndocumentedMatlab.com/images/PropertyGrid_types.png" title="A property grid with spinner control" width="200" height="165" /><p
class="wp-caption-text">A property grid with spinner control</p></div> &nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 289px"><img
alt="JIDE's DateSpinnerComboBox" src="http://UndocumentedMatlab.com/images/DateSpinnerComboBox.png" title="JIDE's DateSpinnerComboBox" width="279" height="228" /><p
class="wp-caption-text">JIDE's DateSpinnerComboBox</p></div></center></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/advanced-jide-property-grids/' rel='bookmark' title='Advanced JIDE Property Grids'>Advanced JIDE Property Grids</a> <small>JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks...</small></li><li><a
href='http://undocumentedmatlab.com/blog/blurred-matlab-figure-window/' rel='bookmark' title='Blurred Matlab figure window'>Blurred Matlab figure window</a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/feed/</wfw:commentRss> <slash:comments>1</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/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/plot-performance/' rel='bookmark' title='Plot performance'>Plot performance</a> <small>Undocumented inner plot mechanisms can be used to significantly improved plotting 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><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></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/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/plot-performance/' rel='bookmark' title='Plot performance'>Plot performance</a> <small>Undocumented inner plot mechanisms can be used to significantly improved plotting 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><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></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>Recovering previous editor state</title><link>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/</link> <comments>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/#comments</comments> <pubDate>Wed, 11 Jan 2012 18:00:49 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Desktop]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Editor]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2656</guid> <description><![CDATA[Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-assign-a-keyboard-macro-in-the-matlab-editor/' rel='bookmark' title='EditorMacro &#8211; assign a keyboard macro in the Matlab editor'>EditorMacro &#8211; assign a keyboard macro in the Matlab editor</a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/non-textual-editor-actions/' rel='bookmark' title='Non-textual editor actions'>Non-textual editor actions</a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li><li><a
href='http://undocumentedmatlab.com/blog/tri-state-checkbox/' rel='bookmark' title='Tri-state checkbox'>Tri-state checkbox</a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><span
class="alignright"><img
title="Editor with multiple loaded documents" src="http://undocumentedmatlab.com/images/editor.png" alt="Editor with multiple loaded documents" width="300" height="380"/></span> I find it very useful to use the Matlab editor&#8217;s ability to load multiple files to help me remember which files I still need to work on. I typically have a few dozen files loaded in the editor. I guess you could say that the editor&#8217;s list of files is a simple reflection of my open tasks. It would be extremely inconvenient if I ever lost this list.</p><p>Which is, unfortunately, exactly what happened to me yesterday.</p><p>I was about to close a figure window and accidentally closed the editor window that was behind it.</p><p>I was now in quite a jam: reopening the editor would not load all my files, but start with a blank (empty) editor. The Matlab editor, unlike modern browsers, does not have a &#8216;reopen last session&#8217; option, and using the most-recently-used (MRU) files list would at best return the latest 9 files (the default Matlab preference is to have an MRU depth of only 4 files, but this is one of the very first things that I change whenever I install Matlab, along with a few other very questionable [IMHO] default preferences).</p><p>Luckily for me, there is an escape hatch: Matlab stores its Desktop windows state in a file called <i>MATLABDesktop.xml</i> that is located in the user&#8217;s <i><b>prefdir</b></i> folder. This file includes information about the position and state (docked/undocked etc.) of every Desktop window. Since the editor files are considered Desktop documents (you can see them under the Desktop&#8217;s main menu&#8217;s Window menu), they are also included in this file. When I closed the Editor, these documents were simply removed from the <i>MATLABDesktop.xml</i> file.</p><p>It turns out that Matlab automatically stores a backup version of this file in another file called <i>MATLABDesktop.xml.prev</i>, in the same <i><b>prefdir</b></i> folder. We can inspect the folder using our system&#8217;s file browser. For example, on Windows we could use:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">winopen<span style="color: #080;">&#40;</span>prefdir<span style="color: #080;">&#41;</span></pre></div></div><p>So before doing anything else, I closed Matlab (I actually crashed it to prevent any cleanup tasks to accidentally erase this backup file, but that turned out to be an unnecessary precaution), deleted the latest <i>MATLABDesktop.xml</i> file, replaced it with a copy of the <i>MATLABDesktop.xml.prev</i> file (which I renamed <i>MATLABDesktop.xml</i>), and only then did I restart Matlab.</p><p>Problem solved &#8211; everything back to normal. Resume breathing. Once again I have my never-ending virtual task list in front of me as I write this.</p><p>Lessons learned:</p><ol><li>don&#8217;t be too quick on the close button trigger</li><li>always keep a relatively recent backup copy of your important config files (BTW, I use the same advice with my FireFox browser, where I normally have dozens of open tabs &#8211; I keep a backup copy of the sessionstore.js file)</li><li>if you do get into a jam, don&#8217;t do anything hasty that might make recovery impossible. Calm down, look around, and maybe you&#8217;ll find an automatic backup somewhere</li></ol><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/editormacro-assign-a-keyboard-macro-in-the-matlab-editor/' rel='bookmark' title='EditorMacro &#8211; assign a keyboard macro in the Matlab editor'>EditorMacro &#8211; assign a keyboard macro in the Matlab editor</a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/non-textual-editor-actions/' rel='bookmark' title='Non-textual editor actions'>Non-textual editor actions</a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li><li><a
href='http://undocumentedmatlab.com/blog/tri-state-checkbox/' rel='bookmark' title='Tri-state checkbox'>Tri-state checkbox</a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/recovering-previous-editor-state/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>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>Converting Java vectors to Matlab arrays</title><link>http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/</link> <comments>http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/#comments</comments> <pubDate>Wed, 14 Dec 2011 18:00:47 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[Undocumented function]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2613</guid> <description><![CDATA[Converting Java vectors to Matlab arrays is pretty simple - this article explains how.<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/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jboost-integrating-an-external-java-library-in-matlab/' rel='bookmark' title='JBoost &#8211; Integrating an external Java library in Matlab'>JBoost &#8211; Integrating an external Java library in Matlab</a> <small>This article shows how an external Java library can be integrated in Matlab...</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>Matlab includes built-in support for automatic conversion of Matlab cell arrays into Java arrays. This is important in cases when we need to pass information to a Java function that expects an array (e.g., <code>String[]</code>).</p><h3 id="Numeric">Numeric data array</h3><p>In some cases, namely Java numeric arrays, Matlab also automatically converts the Java array into Matlab arrays. This is actually inconvenient when we would like to access the original Java reference in order to modify some value &#8211; since the Java reference is inaccessible from Matlab in this case, the data is immutable.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jColor = java.<span style="">awt</span>.<span style="">Color</span>.<span style="">red</span>
jColor =
java.<span style="">awt</span>.<span style="">Color</span><span style="color: #080;">&#91;</span>r=<span style="color: #33f;">255</span>,g=<span style="color: #33f;">0</span>,b=<span style="color: #33f;">0</span><span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; matlabData = jColor.<span style="">getColorComponents</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
matlabData =
     <span style="color: #33f;">1</span>
     <span style="color: #33f;">0</span>     <span style="color: #228B22;">% &lt; = immutable array of numbers, not a reference to int[]</span>
     <span style="color: #33f;">0</span></pre></div></div><h3 id="Nonnumeric">Non-numeric array</h3><p>Very often we encounter cases in Java where the information is stored in an array of non-numeric data. In such cases we need to apply a non-automatic conversion from Java into Matlab.</p><p>If the objects are of exactly the same type, then we could store them in a simple Matlab array; otherwise (as can be seen in the example below), we could store them in either a simple array of <i><b>handle</b></i>s, or in a simple cell array:</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jFrames = java.<span style="">awt</span>.<span style="">Frame</span>.<span style="">getFrames</span>
jFrames =
java.<span style="">awt</span>.<span style="">Frame</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #F0F;">:</span>
    <span style="color: #080;">&#91;</span>javax.<span style="">swing</span>.<span style="">SwingUtilities</span>$SharedOwnerFrame <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMainFrame</span>          <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMultipleClientFrame</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">MJFrame</span>               <span style="color: #080;">&#93;</span>
&nbsp;
<span style="color: #228B22;">% Alternative #1 - use a loop</span>
&gt;&gt; mFrames = handle<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>jFrames<span style="color: #080;">&#41;</span>; mFrames<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span>=handle<span style="color: #080;">&#40;</span>jFrames<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">end</span>
&gt;&gt; mFrames
mFrames =
	handle<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>-by-<span style="color: #33f;">4</span>
&gt;&gt; mFrames<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
	javahandle.<span style="">javax</span>.<span style="">swing</span>.<span style="">SwingUtilities</span>$SharedOwnerFrame
&gt;&gt; mFrames<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
	javahandle.<span style="">com</span>.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMainFrame</span>
&nbsp;
<span style="color: #228B22;">% Alternative #2a - convert into a Matlab cell array</span>
&gt;&gt; mFrames = jFrames.<span style="color: #0000FF;">cell</span>
mFrames = 
    <span style="color: #080;">&#91;</span>1x1 javax.<span style="">swing</span>.<span style="">SwingUtilities</span>$SharedOwnerFrame <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>1x1 com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMainFrame</span>          <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>1x1 com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMultipleClientFrame</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>1x1 com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">MJFrame</span>               <span style="color: #080;">&#93;</span>
&nbsp;
<span style="color: #228B22;">% Alternative #2b - convert to a cell array (equivalent variant of alternative 2a)</span>
&gt;&gt; mFrames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>jFrames<span style="color: #080;">&#41;</span>;</pre></div></div><p>Note that if we only need to access a particular item in the Java vector or array, we could do that directly, without needing to convert the entire data into Matlab first. Simply use <code>jFrames(1)</code> to directly access the first item in the <code>jFrames</code> array, for example.</p><p>(note: Java Frames are discussed in chapters 7 and 8 of my Matlab-Java book).</p><h3 id="Collections">Vectors and other Collections</h3><p>Very often we encounter cases in Java where the information is stored in a <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/collections/index.html">Java Collection</a> rather than in a simple Java array. The basic mechanism for the conversion in this case is to first convert the Java data into a simple Java array (in cases it was not so in the first place), and then to convert this into a Matlab array using either the automated conversion (if the data is numeric), or using a for loop (ugly and slow!), or into a cell array using the <b><i>cell</i></b> function, as explained above.</p><p>Different Collections have different manners of converting into a Java array: some Collections return an Iterator/Enumerator that can be processed in a loop (be careful not to reset the iterator reference by re-reading it within the loop):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Wrong way - causes an infinite loop</span>
idx = <span style="color: #33f;">1</span>;
props = java.<span style="">lang</span>.<span style="">System</span>.<span style="">getProperties</span>;
<span style="color: #0000FF;">while</span> props.<span style="">elements</span>.<span style="">hasMoreElements</span>
    mPropValue<span style="color: #080;">&#123;</span>idx<span style="color: #080;">&#125;</span> = props.<span style="">elements</span>.<span style="">nextElement</span>;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% Right way</span>
idx = <span style="color: #33f;">1</span>;
propValues = java.<span style="">lang</span>.<span style="">System</span>.<span style="">getProperties</span>.<span style="">elements</span>;  <span style="color: #228B22;">% Enumerator</span>
<span style="color: #0000FF;">while</span> propValues.<span style="">hasMoreElements</span>
    mPropValue<span style="color: #080;">&#123;</span>idx<span style="color: #080;">&#125;</span> = propValues.<span style="">nextElement</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>(note: system properties are discussed in section 1.9 of my Matlab-Java book; Collections are discussed in section 2.1)</p><p>Other Collections, such as <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Vector.html"><code>java.util.Vector</code></a>, have a <i>toArray()</i> method that directly converts into a Java array, and we can process from there as described above:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jVector = java.<span style="">util</span>.<span style="">Vector</span>;
&gt;&gt; jVector.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; jVector.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>; jVector.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span>;
&gt;&gt; jVector.<span style="">addAll</span><span style="color: #080;">&#40;</span>jv<span style="color: #080;">&#41;</span>; jVector.<span style="">addAll</span><span style="color: #080;">&#40;</span>jv<span style="color: #080;">&#41;</span>;
&gt;&gt; jVector
jVector =
<span style="color: #080;">&#91;</span><span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span>, <span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span>, <span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span>, <span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span><span style="color: #080;">&#93;</span>
&nbsp;
<span style="color: #228B22;">% Now convert into a Matlab cell array via a Java simple array</span>
&gt;&gt; mCellArray = jVector.<span style="">toArray</span>.<span style="color: #0000FF;">cell</span>
mCellArray = 
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span></pre></div></div><h3 id="Performance">Performance</h3><p>It so happens, that the undocumented built-in <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-feature-function/"><i><b>feature</b></i> function</a> (or its near-synonym <i><b>system_dependent</b></i>) enables improved performance in this conversion process. <i><b>feature</b></i>(44) accepts a <code>java.util.Vector</code> and converts it directly into a Matlab cell-array, in one third to one-half the time that it would take the equivalent <i>toArray.cell()</i> (the third input argument is the number of columns in the result - the reshaping is done automatically):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; mCellArray = feature<span style="color: #080;">&#40;</span><span style="color: #33f;">44</span>,jVector,jVector.<span style="color: #0000FF;">size</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% jVector.size = 12</span>
mCellArray = 
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; mCellArray = feature<span style="color: #080;">&#40;</span><span style="color: #33f;">44</span>,jVector,<span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>
mCellArray = 
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span></pre></div></div><p>The conversion process is pretty efficient: On my system, the regular <i>toArray.cell()</i> takes 0.45 seconds for a 100K vector, compared to 0.21 seconds for the <i><b>feature</b></i> alternative. However, this small difference could be important in cases where performance is crucial, for example in <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/">processing of highly-active Java events in Matlab callbacks</a>, or when retrieving data from a database. And this latter case is indeed where a sample usage of this <i><b>feature</b></i> can be found, namely in the <i><b>cursor.fetch.m</b></i> function (where it appears as <i><b>system_dependent(44)</b></i>).</p><p>Please note that both <i><b>feature</b></i> and <i><b>system_dependent</b></i> are highly prone to change without prior warning in some future Matlab release. On the other hand, the conversion methods that I presented above, excluding <i><b>feature</b></i>, will probably still be valid in all Matlab releases in the near future.</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/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jboost-integrating-an-external-java-library-in-matlab/' rel='bookmark' title='JBoost &#8211; Integrating an external Java library in Matlab'>JBoost &#8211; Integrating an external Java library in Matlab</a> <small>This article shows how an external Java library can be integrated in Matlab...</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/converting-java-vectors-to-matlab-arrays/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Common javacomponent problems</title><link>http://undocumentedmatlab.com/blog/common-javacomponent-problems/</link> <comments>http://undocumentedmatlab.com/blog/common-javacomponent-problems/#comments</comments> <pubDate>Wed, 07 Dec 2011 18:00:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[GUIDE]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2607</guid> <description><![CDATA[The javacomponent function is very useful for placing Java components on-screen, but has a few quirks.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>The <i><b>javacomponent</b></i> function, which I described <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent/">here</a> last year, is a very important built-in Matlab function that enables placing Java components in Matlab figure GUI. Using <i><b>javacomponent</b></i> is pretty straight-forward. However, there are a few quirks that users should be aware of. In today&#8217;s article I&#8217;ll try to highlight some of them and discuss workarounds.</p><h3 id="figure-vis">Figure visibility</h3><p>Java components can only be placed onscreen when their containing Matlab figure has been made visible. This means that calls to <i><b>javacomponent</b></i> cannot be placed at the GUIDE-created *_OpeningFcn() function, because that function is invoked <i>before</i> the figure window is made visible.</p><p>Of course, we can always force the figure to become visible by setting the figure&#8217;s <b>Visible</b> property to <code>'on'</code> in this function, before calling our <i><b>javacomponent</b></i>s. But IMHO, a better option would be to simply place the <i><b>javacomponent</b></i>s in the corresponding GUIDE-created *_OutputFcn() function, which is invoked <i>after</i> the figure window is made visible.</p><h3 id="parent-vis">Auto-hiding with parent container</h3><p>Java components are not automatically hidden with their ancestor container panel. This is also the root cause of the failure of Java components to disappear when switching tabs in a <i><b>uitab</b></i>.</p><p>One simple workaround for this that I often use is to link the <b>Visible</b> properties of the <i><b>javacomponent</b></i> container and the parent container:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, hParent<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span>hParent, <span style="color:#A020F0;">'linked_props__'</span>, linkprop<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>hParent,hContainer<span style="color: #080;">&#93;</span>,<span style="color:#A020F0;">'Visible'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This has indeed been fixed in R2010b. If you ask me, this should have been standard behavior of <i><b>javacomponent</b></i> since the very beginning&#8230;</p><p>Although there is no need for the workaround in R2010b onward, I usually keep the workaround because it doesn&#8217;t hurt and enables backward compatibility for users who may have an older Matlab release.</p><h3 id="parent-types">Possible parent container types</h3><p><i><b>javacomponent</b></i> accepts parent handles that are figures, toolbars, <i><b>uipanel</b></i>s, or <a
target="_blank" href="http://UndocumentedMatlab.com/blog/matlab-layout-managers-uicontainer-and-relatives"><i><b>uicontainer</b></i>s</a> (some of these are not documented as possible parents in some Matlab releases, but they are). Since R2008a, parents of type <a
target="_blank" href="http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/"><i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i></a> can also be used. Unfortunately, frames are not <i><b>uicontainer</b></i>s and, therefore, cannot be used as <i><b>javacomponent</b></i> parents.</p><p>Note: Due to a bug in R2007a, <i><b>javacomponent</b></i>s cannot be added to <i><b>uicontainer</b></i>s, since <i>javacomponent.m</i> checks if <code>isa(hParent,'uicontainer')</code> (and similarly for <code>'uiflowcontainer', 'uigridcontainer'</code>), instead of <code>isa(hParent,'hg.uicontainer')</code> (and similarly for the others). If we modify <i>javacomponent.m</i> accordingly (add &#8220;hg.&#8221; in lines 98-100), this bug will be fixed. Since R2007b, <code>isa(…,'hg.uicontainer')</code> is equivalent to <code>isa(…,'uicontainer')</code>, so this fix is unnecessary.</p><h3 id="inputs">Input parameters</h3><p>Unlike many other Matlab functions, <i><b>javacomponent</b></i> does not accept optional parameter-value (P-V) pairs. If we want to customize the appearance of the Java component, it is better to create it , customize it, and only then to present it onscreen using <i><b>javacomponent</b></i>. If we first present the component and then customize it, there might be all sorts of undesirable flicker effects while the component is changing its properties.</p><p>One of the parameters that unfortunately cannot be customized before calling <i><b>javacomponent</b></i> is the component&#8217;s position onscreen. <i><b>javacomponent</b></i> only accepts a position vector in pixel units. To modify the component to use normalized units, we need to modify the container&#8217;s properties:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hContainer, <span style="color:#A020F0;">'Units'</span>,<span style="color:#A020F0;">'norm'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Similarly, we can set the container&#8217;s <b>UserData</b> and <b>ApplicationData</b> only after the call to <i><b>javacomponent</b></i>.</p><h3 id="bg-color">Background color</h3><p>The default background color of <i><b>javacomponent</b></i>s is a slightly different shade of gray than the default <i><b>uicontrol</b></i> background color. Please refer to my recent <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent-background-color/">article</a> for a detailed discussion of this issue.</p><h3 id="alignment">Vertical alignment</h3><p>Java components are slightly mis-aligned vertically with combo-box (<b>Style</b>=&#8217;popup&#8217;) <i><b>uicontrol</b></i>s, even when positioned using the same Y position. This is actually due to an apparent bug in Matlab&#8217;s implementation of the combo-box <i><b>uicontrol</b></i>, and not in the Java component&#8217;s: Apparently, the Matlab control does not obey its specified height and uses some other default height.</p><p>If we place <i><b>javacomponent</b></i>s side-by-side with a regular Matlab popup <i><b>uicontrol</b></i>s and give them all the same Y position, we can see this mis-alignment. It is only a few pixels, but the effect is visible and disturbing. To fix it, we need to add a small offset to the <i><b>javacomponent</b></i>&#8216;s container&#8217;s <b>Position</b> property to make both the initial Y position slightly lower, and the height value slightly higher than the values for the corresponding Matlab combo-box control.</p><h3 id="callbacks">Callbacks</h3><p>Unlike Matlab <i><b>uicontrol</b></i> callbacks, Java callbacks are activated even when the affected value does not change. Therefore, setting a value in the component&#8217;s callback could well cause an infinite loop of invoked callbacks.</p><p>Matlab programmers often use the practice of modifying component value within the callback function, as a means of fixing user-entered values to be within a certain data range, or in order to format the displayed value. This is relatively harmless in Matlab (if done correctly) since updating a Matlab <i><b>uicontrol</b></i>&#8216;s value to the current value does not retrigger the callback. But since this is not the case with Java callbacks, users should beware not to use the same practice there. In cases where this cannot be avoided, users should at least implement some sort of <a
target="_blank" href="http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/">callback re-entrancy prevention logic</a>.</p><h3 id="EDT">EDT</h3><p>Java components typically need to use the independent Java Event processing Thread (EDT). EDT is very important for Matlab GUI, as explained in <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/">this article</a>. Failure to use EDT properly in Matlab can lead to unexpected GUI behavior and even Matlab hangs or crashes.</p><p>If the <i><b>javacomponent</b></i> function is called in a very specific syntax format where the first input arg is a string (the name of the Java class to be created), then the newly-created component is placed on the EDT. However, this is not the normal manner in which <i><b>javacomponent</b></i> is used: A much more typical use-case is where <i><b>javacomponent</b></i> is passed a reference handle to a previously-created Java component. In such cases, it is the user&#8217;s responsibility to place the component on the EDT. Until R2008a this should be done using the <i><b>awtcreate</b></i> function; since R2008b, we can use the much simpler <i><b>javaObjectEDT</b></i> function (<i><b>javaObjectEDT</b></i> actually existed since R2008a, but was buggy on that release so I suggest using it only starting in R2008b; it became documented starting in R2009a). In fact, modern <i><b>javacomponent</b></i> saves us the trouble, by automatically using <i><b>javaObjectEDT</b></i> to auto-delegate the component onto the EDT, even if we happen to have created it on the MT.</p><p>The paragraph above may lead us to believe that we only need to worry about EDT in R2008a and earlier. Unfortunately, this is not the case. Modern GUI requires using many sub-components, that are attached to their main component (e.g., CellRenderers and CellEditors). <i><b>javacomponent</b></i> only bothers to place the main component on the EDT &#8211; not any of the sub-components. We need to handle these separately. Liberally auto-delegating components to the EDT seems like a safe and painless habit to have.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/common-javacomponent-problems/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Types of undocumented Matlab aspects</title><link>http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/</link> <comments>http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/#comments</comments> <pubDate>Thu, 24 Nov 2011 18:00:36 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented feature]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Undocumented function]]></category> <category><![CDATA[Hidden property]]></category> <category><![CDATA[Internal component]]></category> <category><![CDATA[JMI]]></category> <category><![CDATA[Pure Matlab]]></category> <category><![CDATA[Undocumented property]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2534</guid> <description><![CDATA[This article lists the different types of undocumented/unsupported/hidden aspects in Matlab<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/reasons-for-undocumented-matlab-aspects/' rel='bookmark' title='Reasons for undocumented Matlab aspects'>Reasons for undocumented Matlab aspects</a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-cursorbar-object/' rel='bookmark' title='Undocumented cursorbar object'>Undocumented cursorbar object</a> <small>Matlab's internal undocumented graphics.cursorbar object can be used to present dynamic data-tip cross-hairs...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uiundo-matlab-undocumented-undo-redo-manager/' rel='bookmark' title='uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager'>uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager</a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Why are there so many undocumented aspects in Matlab?</p><p>This is a great question, recently <a
target="_blank" href="http://undocumentedmatlab.com/blog/guide-customization/#comment-61578">asked</a> by a reader of this blog, so I wanted to expand on it in next week&#8217;s article. Before specifying the different reasons, let&#8217;s map the nature of undocumented aspects that we find in Matlab.</p><p>The term <i>undocumented/unsupported</i> (as opposed to <i>mis-documentated</i> or <i>deprecated</i>) actually refers to quite a large number of different types.<br
/> In the following list, the hyperlinks on the list-item titles lead to a list of corresponding articles on this website:</p><ul><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-function/">Undocumented functions</a></b><br
/> Matlab functions which appears nowhere in the documentation, are usually built-in functions (do not have an m-file) and can only be inferred from online CSSM posts or usage within one of the Matlab m-functions installed with Matlab (the latter being the usual case). None of these functions is officially supported by MathWorks. <a
target="_blank" href="http://undocumentedmatlab.com/blog/category/mex/">MEX</a> is an important source for such functions.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/semi-documented-function/">Semi-documented functions</a></b><br
/> Matlab functionality which exists in Matlab m-functions installed with Matlab, but have their main comment separated from the H1 comment line, thereby hiding it from normal view (via Matlab&#8217;s <i><b>help</b></i> function). The H1 comment line itself is simply a standard warning that this function is not officially supported and may change in some future version. To see the actual help comment, simply edit the function (using Matlab&#8217;s <i><b>edit</b></i> function or any text editor) and place a comment sign (%) at the empty line between the H1 comment and the actual help section. The entire help section will then onward be visible via the <i><b>help</b></i> function:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">        <span style="color: #0000FF;">function</span> <span style="color: #080;">&#91;</span>tree, container<span style="color: #080;">&#93;</span> = uitree<span style="color: #080;">&#40;</span><span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
        <span style="color: #228B22;">% WARNING: This feature is not supported in MATLAB</span>
        <span style="color: #228B22;">% and the API and functionality may change in a future release.</span>
<span style="color: #0000FF;">fix</span> =&gt;  <span style="color: #228B22;">%</span>
        <span style="color: #228B22;">% UITREE creates a uitree component with hierarchical data in a figure window.</span>
        <span style="color: #228B22;">%   UITREE creates an empty uitree object with default property values in</span>
        <span style="color: #228B22;">%   a figure window.</span>
        <span style="color: #228B22;">%...</span></pre></div></div><p>These functions are not documented in the full documentation (via Matlab&#8217;s <i><b>doc</b></i> function, or online). The odd thing is that some of these functions may appear in the category help output (for example, <i><b>help</b>(&#8216;uitools&#8217;)</i>), and in some cases may even have a fully-visible help section (e.g., <i><b>help</b>(&#8216;setptr&#8217;)</i>), but do not have any online help documentation (<i><b>docsearch</b>(&#8216;setptr&#8217;)</i> fails, and <i><b>doc</b>(&#8216;setptr&#8217;)</i> simply displays the readable help text).</p><p>All these functions are officially unsupported by MathWorks, even when having a readable help section. The rule of thumb appears to be that a Matlab function is supported only if it has online documentation. Note, however, that in some rare cases a documentation discrepancy may be due to a MathWorks documentation error, not to unsupportability&#8230;</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-function/">Helper functions</a></b><br
/> Many fully-supported Matlab functions use helper functions that have a specific use in the main (documented) function(s).  Often, these helper functions are tightly-coupled to their documented parents and are useless as stand-alone functions. But quite a few of them have quite useful stand-alone use, as I&#8217;ve already shown in some past articles.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-feature/">Undocumented features</a> and <a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-property/">properties</a></b><br
/> Features of otherwise-documented Matlab functions, which appear nowhere in the official documentation. You guessed it – these are also not supported by MathWorks&#8230; Like undocumented functions, you can only infer such features by the occasional CSSM post or a reference somewhere in Matlab&#8217;s m-code.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/semi-documented-feature/">Semi-documented features</a></b><br
/> Features of otherwise-documented Matlab functions, which are documented in a separate section beneath the main help section, and nowhere else (not in the full doc not the online documentation). If you did not know in advance that these features existed, you could only learn of them by manually looking at Matlab&#8217;s m-files (which is what I do in most cases&#8230;).</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/undocumented-property/">Undocumented properties</a></b><br
/> Many Matlab objects have internal properties, which can be retrieved (via Matlab&#8217;s <i><b>get</b></i> function) and/or set (via the <i><b>set</b></i> function) programmatically. All these properties are fully documented. Many objects also possess hidden properties, some of which are very interesting and useful, but which are undocumented and (oh yes) unsupported. Like undocumented features, they can only be inferred from CSSM or existing code. In a recent <a
target="_blank" href="http://undocumentedmatlab.com/blog/getundoc-get-undocumented-object-properties/">article</a> I described my <i><b>getundoc</b></i> utility, which lists these undocumented properties of specified objects.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/internal-component/">Internal Matlab classes</a></b><br
/> Matlab uses a vast array of specialized Java classes to handle everything from algorithms to GUI. These classes are (of course) undocumented/unsupported. They can often be accessed directly from the Matlab Command Window or user m-files. GUI classes can be inferred by inspecting the figure frame&#8217;s Java components, and non-GUI classes can often be inferred from references in Matlab&#8217;s m-files.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/JMI">Matlab-Java integration</a></b><br
/> Matlab&#8217;s GUI interface, as well as the Java-to-Matlab interface (JMI) is fully undocumented and unsupported. In addition to JMI, there are other mechanisms to run Matlab code from within Java (namely JMI, COM and DDE) &#8211; these are all unsupported and by-and-large undocumented.</p></li><li><b><a
target="_blank" href="http://undocumentedmatlab.com/?s=UDD">Matlab&#8217;s UDD mechanism</a></b><br
/> UDD (Unified Data Definition?) is used extensively in Matlab as the internal object-oriented mechanism for describing object properties and functionalities. We can use UDD for a wide variety of uses. UDD was described in a series of articles here in early 2011.</li></ul><p>Next week I will list the reasons that cause MathWorks to decide whether a particular feature or property should be documented or not.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/reasons-for-undocumented-matlab-aspects/' rel='bookmark' title='Reasons for undocumented Matlab aspects'>Reasons for undocumented Matlab aspects</a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-cursorbar-object/' rel='bookmark' title='Undocumented cursorbar object'>Undocumented cursorbar object</a> <small>Matlab's internal undocumented graphics.cursorbar object can be used to present dynamic data-tip cross-hairs...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uiundo-matlab-undocumented-undo-redo-manager/' rel='bookmark' title='uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager'>uiundo &#8211; Matlab&#8217;s undocumented undo/redo manager</a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/types-of-undocumented-matlab-aspects/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>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/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/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/plot-liminclude-properties/' rel='bookmark' title='Plot LimInclude properties'>Plot LimInclude properties</a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li></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/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/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/plot-liminclude-properties/' rel='bookmark' title='Plot LimInclude properties'>Plot LimInclude properties</a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li></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> </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-02-09 05:14:10 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/category/presumed-future-risk/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      1.924s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1328789648; expires=Fri, 08-Feb-2013 12:14:08 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Thu, 09 Feb 2012 12:14:10 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Thu, 09 Feb 2012 13:14:10 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               fafff5bd20adfab2750545af06b1a6b3
Content-Encoding:   gzip
-->
