<?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 function &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/undocumented-function/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Tue, 24 Oct 2017 12:43:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>The HotLinks feature</title>
		<link>https://undocumentedmatlab.com/articles/the-hotlinks-feature?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-hotlinks-feature</link>
					<comments>https://undocumentedmatlab.com/articles/the-hotlinks-feature#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Tue, 24 Oct 2017 12:43:13 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7128</guid>

					<description><![CDATA[<p>feature('HotLinks') can be used to temporarily disable hyperlinks and other markups in the Matlab console. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/the-hotlinks-feature">The HotLinks feature</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-function" rel="bookmark" title="Undocumented feature() function">Undocumented feature() function </a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/legend-semi-documented-feature" rel="bookmark" title="Legend &#039;-DynamicLegend&#039; semi-documented feature">Legend &#039;-DynamicLegend&#039; semi-documented feature </a> <small>The built-in Matlab legend function has a very useful semi-documented feature for automatic dynamic update, which is explained here....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Back in 2010, I posted about <a href="/articles/undocumented-feature-function" target="_blank">Matlab&#8217;s undocumented <i><b>feature</b></i> function</a>. One of the features that I mentioned was <code>'HotLinks'</code>. A few days ago I had an occasion to remember this feature when a <a href="https://stackoverflow.com/questions/46676035/how-do-i-change-the-fontweight-of-table-titles-in-matlab" rel="nofollow" target="_blank">StackOverflow user complained</a> that the headers of <i><b>table</b></i> outputs in the Matlab console appear with HTML tags (&lt;strong&gt;) in his <i><b>diary</b></i> output. He asked whether it was possible to turn off this automated headers markup.<br />
There are several ways this problem can be solved, ranging from creating a custom table display function, to modifying the table&#8217;s internal <i>disp</i> method (<i>%matlabroot%/toolbox/matlab/datatypes/@tabular/disp.m</i>), to using this method&#8217;s second optional argument (<code>disp(myTable,false)</code>). Note that simply subclassing the <code>table</code> class to overload <i>disp()</i> will not work because the <code>table</code> class is Sealed, but we could instead subclass <code>table</code>&#8216;s superclass (<code>tabular</code>) just like <code>table</code> does.<br />
Inside the <i>disp.m</i> method mentioned above, the headers markup is controlled (around line 45, depending on your Matlab release) by <code>matlab.internal.display.isHot</code>. Unfortunately, there is no corresponding <i>setHot()</i> method, nor corresponding m- or p-code that can be inspected. But the term &#8220;Hot&#8221; rang a bell, and then I remembered my old post about the HotLinks feature, which is apparently reflected by <code>matlab.internal.display.isHot</code>.</p>
<pre lang="matlab">
feature('HotLinks',false);  % temporarily disable bold headers and hyperlinks (matlab.internal.display.isHot=false)
disp(myTable)
myTable        % this calls disp() implicitly
feature('HotLinks',true);   % restore the standard behavior (markup displayed, matlab.internal.display.isHot=true)
</pre>
<p>Searching for &#8220;isHot&#8221; or &#8220;HotLinks&#8221; under the Matlab installation folder, we find that this feature is used in hundreds of places (the exact number depends on your installed toolboxes). The general use appears to be to disable/enable output of hyperlinks to the Matlab console, such as when you display a Matlab class, when its class name is hyperlinked and so is the &#8220;Show all properties&#8221; message at the bottom. But in certain cases, such as for the <code>table</code> output above, the feature is also used to determine other types of markup (bold headers in this case).<br />
<span id="more-7128"></span></p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; feature<span style="color: #080;">(</span><span style="color:#A020F0;">'HotLinks'</span>,<span style="color: #33f;">0</span><span style="color: #080;">)</span>  <span style="color: #228B22;">% temporarily disable bold headers and hyperlinks</span>
&gt;&gt; groot
ans =
  Graphics Root with properties:
&nbsp;
          CurrentFigure: [0×0 GraphicsPlaceholder]
    ScreenPixelsPerInch: 96
             ScreenSize: [1 1 1366 768]
       MonitorPositions: [2×4 double]
                  Units: 'pixels'
&nbsp;
  Use GET to show all properties
&gt;&gt; feature<span style="color: #080;">(</span><span style="color:#A020F0;">'HotLinks'</span>,<span style="color: #33f;">1</span><span style="color: #080;">)</span>  <span style="color: #228B22;">% restore the standard behavior (markup displayed)</span>
&gt;&gt; groot
ans =
  Graphics <span style="color: #0000FF;"><u>Root</u></span> with properties:
&nbsp;
          CurrentFigure: [0×0 GraphicsPlaceholder]
    ScreenPixelsPerInch: 96
             ScreenSize: [1 1 1366 768]
       MonitorPositions: [2×4 double]
                  Units: 'pixels'
&nbsp;
  Show <span style="color: #0000FF;"><u>all properties</u></span></pre>
</div>
</div>
<p>There&#8217;s nothing really earth shuttering in all this, but the HotLinks feature could be useful when outputting console output into a diary file. Of course, if <i><b>diary</b></i> would have automatically stripped away markup tags we would not need to resort to such hackery. Then again, this is not the only problem with <i><b>diary</b></i>, which is <a href="/articles/couple-of-matlab-bugs-and-workarounds#comment-340803" target="_blank">long-overdue an overhaul</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/the-hotlinks-feature">The HotLinks feature</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-function" rel="bookmark" title="Undocumented feature() function">Undocumented feature() function </a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/legend-semi-documented-feature" rel="bookmark" title="Legend &#039;-DynamicLegend&#039; semi-documented feature">Legend &#039;-DynamicLegend&#039; semi-documented feature </a> <small>The built-in Matlab legend function has a very useful semi-documented feature for automatic dynamic update, which is explained here....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/the-hotlinks-feature/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Runtime code instrumentation</title>
		<link>https://undocumentedmatlab.com/articles/runtime-code-instrumentation?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=runtime-code-instrumentation</link>
					<comments>https://undocumentedmatlab.com/articles/runtime-code-instrumentation#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 28 Sep 2017 13:36:17 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[File Exchange]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7063</guid>

					<description><![CDATA[<p>Conditional breakpoints can be used to instrument code with user-specified code. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/runtime-code-instrumentation">Runtime code instrumentation</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output" rel="bookmark" title="Parsing mlint (Code Analyzer) output">Parsing mlint (Code Analyzer) output </a> <small>The Matlab Code Analyzer (mlint) has a lot of undocumented functionality just waiting to be used. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/running-vb-code-in-matlab" rel="bookmark" title="Running VB code in Matlab">Running VB code in Matlab </a> <small>Matlab does not natively enable running VB code, but a nice trick enables us to do just that...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I regularly follow the MathWorks <a href="https://blogs.mathworks.com/pick" rel="nofollow" target="_blank">Pick-of-the-Week (POTW) blog</a>. In a <a href="https://blogs.mathworks.com/pick/2017/08/11/trace-your-calls-to-your-methods" rel="nofollow" target="_blank">recent post</a>, Jiro Doke highlighted Per Isakson&#8217;s <a href="http://www.mathworks.com/matlabcentral/fileexchange/28929-tracer4m" rel="nofollow" target="_blank"><i><b>tracer4m</b></i></a> utility. Per is an accomplished Matlab programmer, who has a solid reputation in the Matlab user community for many years. His utility uses temporary conditional breakpoints to enable users to trace calls to their Matlab functions and class methods. This uses a little-known trick that I wish to highlight in this post.<br />
<center><figure style="width: 430px" class="wp-caption aligncenter"><a href="http://www.mathworks.com/matlabcentral/fileexchange/28929-tracer4m" rel="nofollow" target="_blank"><img decoding="async" alt="tracer4m utility uses conditional breakpoints that evaluate but never become live" src="https://www.mathworks.com/matlabcentral/mlc-downloads/downloads/submissions/28929/versions/3/screenshot.png" title="tracer4m utility uses conditional breakpoints that evaluate but never become live" width="430" hight="353"/></a><figcaption class="wp-caption-text">tracer4m utility uses conditional breakpoints that evaluate but never become live</figcaption></figure></center><br />
Matlab breakpoints are documented and supported functionality, and yet their documented use is typically focused at interactive programming in the Matlab editor, or as interactive commands that are entered in the Matlab console using the set of db* functions: <i><b>dbstop</b></i>, <i><b>dbclear</b></i>, <i><b>dbstatus</b></i>, <i><b>dbstack</b></i> etc. However, nothing prevents us from using these db* functions directly within our code.<br />
<span id="more-7063"></span><br />
For example, the <i><b>dbstack</b></i> function can help us diagnose the calling tree for the current function, in order to do action A if one of the calling ancestors was FunctionX, or to do action B otherwise (for example, to avoid nested recursions).<br />
Similarly, we could add a programmatic call to <i><b>dbstop</b></i> in order to stop at a certain code location downstream (for debugging), if a certain condition happens upstream.<br />
Per extended this idea very cleverly in <i><b>tracer4m</b></i>: conditional breakpoints evaluate a string in run-time: if the result is true (non-zero) then the code run is stopped at that location, but if it&#8217;s false (or zero) then the code run continues normally. To instrument calls to specific functions, Per created a function <code>tracer()</code> that logs the function call (using <i><b>dbstack</b></i>) and always returns the value <code>false</code>. He then dynamically created a string that contains a call to this new function and used the <i><b>dbstop</b></i> function to create a conditional breakpoint based on this function, something similar to this:</p>
<pre lang="matlab">dbstop('in', filename, 'at', location, 'if', 'tracer()');</pre>
<p>We can use this same technique for other purposes. For example, if we want to do some action (not necessarily log &#8211; perhaps do something else) when a certain code point is reached. The benefit here is that we don&#8217;t need to modify the code at all &#8211; we&#8217;re adding ad-hoc code pieces using the conditional breakpoint mechanism without affecting the source code. This is particularly useful when we do not have access to the source code (such as when it&#8217;s compiled or write-protected). All you need to do is to ensure that the instrumentation function always returns <code>false</code> so that the breakpoint does not become live and for code execution to continue normally.<br />
The <i><b>tracer4m</b></i> utility is quite sophisticated in the sense that it uses <i><b>mlint</b></i> and smart <i><b>regexp</b></i> to parse the code and know which functions/methods occur on which line numbers and have which type (<a href="/articles/parsing-mlint-code-analyzer-output" target="_blank">more details</a>). In this sense, Per used undocumented functionality. I&#8217;m certain that Jiro was not aware of the dependency on undocumented features when he posted about the utility, so please don&#8217;t take this to mean that Jiro or MathWorks officially support this or any other undocumented functionality. Undocumented aspects are often needed to achieve top functionality, and I&#8217;m happy that the POTW blog highlights utilities based on their importance and merit, even if they do happen to use some undocumented aspect.<br />
<i><b>tracer4m</b></i>&#8216;s code also contains references to the <a href="/articles/undocumented-profiler-options-part-3" target="_blank">undocumented profiler option <code>-history</code></a>, but this is not in fact used by the code itself, only in comments. I use this feature in my <a href="/articles/function-call-timeline-profiling" target="_blank">profile_history utility</a>, which displays the function call/timing history in an interactive GUI window. This utility complements <i><b>tracer4m</b></i> by providing a lot more information, but this can result in a huge amount of information for large and/or long-running programs. In addition, <i><b>tracer4m</b></i> has the benefit of only logging those functions/methods that the user finds useful, rather than all the function call, which enables easier debugging when the relevant code area is known. In short, I wish I had known about <i><b>tracer4m</b></i> when I created <i><b>profile_history</b></i>. Now that I know about it, maybe I&#8217;ll incorporate some of its ideas into <i><b>profile_history</b></i> in order to make it more useful. Perhaps another moral of this is that we should actively monitor the POTW blog, because true gems are quite often highlighted there.<br />
<center><a target="_blank" href="/articles/function-call-timeline-profiling"><img decoding="async" alt="Function call timeline profiling" src="https://undocumentedmatlab.com/images/profile_history.png" title="Function call timeline profiling" width="100%" style="max-width: 658px;" /></a><br />
Function call timeline profiling</center><br />
<!-- center>[caption id="" align="aligncenter" width="500" caption="Function call timeline profiling"]<a target="_blank" href="/articles/function-call-timeline-profiling"><img fetchpriority="high" decoding="async" alt="Function call timeline profiling" src="https://undocumentedmatlab.com/images/profile_history.png" title="Function call timeline profiling" width="500" height="410" /></a>[/caption]</center --><br />
For anyone who missed the announcement in my previous post, I&#8217;m hosting a series of live <a href="/articles/advanced-matlab-online-webinars" target="_blank">webinars on advanced Matlab topics</a> in the upcoming 2 weeks &#8211; I&#8217;ll be happy if you would join.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/runtime-code-instrumentation">Runtime code instrumentation</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output" rel="bookmark" title="Parsing mlint (Code Analyzer) output">Parsing mlint (Code Analyzer) output </a> <small>The Matlab Code Analyzer (mlint) has a lot of undocumented functionality just waiting to be used. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/running-vb-code-in-matlab" rel="bookmark" title="Running VB code in Matlab">Running VB code in Matlab </a> <small>Matlab does not natively enable running VB code, but a nice trick enables us to do just that...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/runtime-code-instrumentation/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>MathWorks-solicited Java survey</title>
		<link>https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mathworks-solicited-java-survey</link>
					<comments>https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 22 Mar 2017 22:05:34 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[uifigure]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6866</guid>

					<description><![CDATA[<p>MathWorks is soliciting user feedbacks about the use of Java components in Matlab programs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey">MathWorks-solicited Java survey</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/mathworks-blogs-facelift" rel="bookmark" title="MathWorks blogs facelift">MathWorks blogs facelift </a> <small>MathWorks has just released a new look-&-feel for their blogs section. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-a-java-focus-problem" rel="bookmark" title="Fixing a Java focus problem">Fixing a Java focus problem </a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Over the years I&#8217;ve reported numerous uses for integrating Java components and functionality in Matlab. As I&#8217;ve also <a href="/articles/adding-a-search-box-to-figure-toolbar#uifigure" rel="nofollow" target="_blank">recently reported</a>, MathWorks is apparently making a gradual shift away from standalone Java-based figures, toward browser-based web-enabled figures. <a href="/articles/password-and-spinner-controls-in-matlab-gui#warning" target="_blank">As I surmised</a> a few months ago, MathWorks has created dedicated surveys to solicit user feedbacks on the most important (and undocumented) non-compatible aspects of this paradigm change: one regarding users&#8217; use of the <a href="/articles/javacomponent" rel="nofollow" target="_blank"><i><b>javacomponent</b></i> function</a>, the other regarding the use of the figure&#8217;s <a href="/articles/tag/javaframe" target="_blank"><b>JavaFrame</b> property</a>:</p>
<ul>
<li>Survey regarding usage of the <i><b>javacomponent</b></i> function: <a href="http://www.mathworks.com/javacomponent" rel="nofollow" target="_blank">http://www.mathworks.com/javacomponent</a></li>
<li>Survey regarding usage of the <b>JavaFrame</b> property: <a href="http://www.mathworks.com/javaframe" rel="nofollow" target="_blank">http://www.mathworks.com/javaframe</a></li>
</ul>
<p>In MathWorks&#8217; words:</p>
<blockquote><p>
In order to extend your ability to build MATLAB apps, we understand you sometimes need to make use of undocumented Java UI technologies, such as the JavaFrame property. In response to your needs, we are working to develop documented alternatives that address gaps in our app building offerings.<br />
To help inform our work and plans, we would like to understand how you are using the JavaFrame property. Based on your understanding of how it is being used within your app, please take a moment to fill out the following survey. The survey will take approximately 1-2 minutes to finish.
</p></blockquote>
<p>I urge anyone who uses one or both of these features to let MathWorks know how you&#8217;re using them, so that they could incorporate that functionality into the core (documented) Matlab. The surveys are really short and to the point. If you wish to send additional information, please email George.Caia at mathworks.com.<br />
The more feedback responses that MathWorks will get, the better it will be able to prioritize its R&#038;D efforts for the benefit of all users, and the more likely are certain features to get a documented solution at some future release. If you don&#8217;t take the time now to tell MathWorks how you use these features in your code, don&#8217;t complain if and when they break in the future&#8230;</p>
<h3 id="uses">My personal uses of these features</h3>
<ul>
<li><b>Functionality:</b>
<ul>
<li>Figure: maximize/minimize/restore, enable/disable, always-on-top, toolbar controls, menu customizations (icons, tooltips, font, shortcuts, colors)</li>
<li>Table: sorting, filtering, grouping, column auto-sizing, cell-specific behavior (tooltip, context menu, context-sensitive editor, merging cells)</li>
<li>Tree control</li>
<li>Listbox: cell-specific behavior (tooltip, context menu)</li>
<li>Tri-state checkbox</li>
<li>uicontrols in general: various event callbacks (e.g. mouse hover/unhover, focus gained/lost)</li>
<li>Ability to add Java controls e.g. color/font/date/file selector panel or dropdown, spinner, slider, search box, password field</li>
<li>Ability to add 3rd-party components e.g. JFreeCharts, JIDE controls/panels</li>
</ul>
<p></li>
<li><b>Appearance:</b>
<ul>
<li>Figure: undecorated (frameless), other figure frame aspects</li>
<li>Table: column/cell-specific rendering (alignment, icons, font, fg/bg color, string formatting)</li>
<li>Listbox: auto-hide vertical scrollbar as needed, cell-specific renderer (icon, font, alignment, fg/bg color)</li>
<li>Button/checkbox/radio: icons, text alignment, border customization, Look &#038; Feel</li>
<li>Right-aligned checkbox (button to the right of label)</li>
<li>Panel: border customization (rounded/matte/&#8230;)</li>
</ul>
</li>
</ul>
<p>You can find descriptions/explanations of many of these in posts I made on this website over the years.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey">MathWorks-solicited Java survey</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/mathworks-blogs-facelift" rel="bookmark" title="MathWorks blogs facelift">MathWorks blogs facelift </a> <small>MathWorks has just released a new look-&-feel for their blogs section. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-a-java-focus-problem" rel="bookmark" title="Fixing a Java focus problem">Fixing a Java focus problem </a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Checking status of warning messages in MEX</title>
		<link>https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=checking-status-of-warning-messages-in-mex</link>
					<comments>https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 21 Dec 2016 15:24:06 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Pavel Holoborodko]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6797</guid>

					<description><![CDATA[<p>Undocumented Mex functions can be used to extract the state of Matlab warnings in run-time. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex">Checking status of warning messages in MEX</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/better-mex-error-messages" rel="bookmark" title="Better MEX error messages">Better MEX error messages </a> <small>The default clunky and release-incompatible MEX error messages can be improved using a simple hack. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-text" rel="bookmark" title="Setting status-bar text">Setting status-bar text </a> <small>The Matlab desktop and figure windows have a usable statusbar which can only be set using undocumented methods. This post shows how to set the status-bar text....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-components" rel="bookmark" title="Setting status-bar components">Setting status-bar components </a> <small>Matlab status-bars are Java containers in which we can add GUI controls such as progress-bars, not just simple text labels...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sending-email-text-messages-from-matlab" rel="bookmark" title="Sending email/text messages from Matlab">Sending email/text messages from Matlab </a> <small>Sending emails and SMS (text) messages from Matlab is easy, once you know a few quirks....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I would like to welcome guest blogger Pavel Holoborodko, the developer of the <a href="http://advanpix.com" rel="nofollow" target="_blank">Advanpix Multiprecision Computing Toolbox</a>. Pavel has <a href="/articles/tag/pavel-holoborodko" target="_blank">already posted here</a> as a guest blogger about undocumented Matlab MEX functions. Today he will discuss another little-known aspect of advanced MEX programming with Matlab, a repost of an article that was <a href="http://www.advanpix.com/2016/10/24/check-status-of-warning-messages-from-mex" rel="nofollow" target="_blank">originally posted</a> on his own blog. Happy holidays everybody!</i><br />
Matlab allows flexible adjustment of visibility of warning messages. Some, or even all, messages can be disabled from showing on the screen by <i><b><a href="https://www.mathworks.com/help/matlab/matlab_prog/suppress-warnings.html" rel="nofollow" target="_blank">warning</a></b></i> command.<br />
The little known fact is that status of some warnings may be used to change the execution path in algorithms. For example, if warning <code>'Matlab:nearlySingularMatrix'</code> is disabled, then the linear system solver (<i><b>mldivide</b></i> operator) might skip estimation of reciprocal condition number which is used exactly for the purpose of detection of nearly singular matrices. If the trick is used, it allows 20%-50% boost in solver performance, since <code>rcond</code> estimation is a time consuming process.<br />
Therefore it is important to be able to retrieve status of warnings in Matlab. Especially in MEX libraries targeted for improved performance. Unfortunately Matlab provides no simple way to check status of warning message from MEX module.<br />
Today&#8217;s article outlines two workarounds for the issue:</p>
<ol>
<li>Using <code>mexCallMATLABWithTrap</code> (documented)</li>
<li>Using <code>utGetWarningStatus</code> (undocumented)</li>
</ol>
<p><span id="more-6797"></span></p>
<h3 id="mexCallMATLABWithTrap">Using mexCallMATLABWithTrap (documented)</h3>
<p>The first idea is to use documented <a href="https://www.mathworks.com/help/matlab/apiref/mexcallmatlabwithtrap.html" rel="nofollow" target="_blank"><code>mexCallMATLABWithTrap</code></a> function to execute <i><b>warning</b>(&#8216;query&#8217;,&#8230;)</i> command using Matlab&#8217;s interpreter and then parse the returned result:</p>
<pre lang="cpp">
bool mxIsWarningEnabled(const char* warningId)
{
    bool enabled = true;
    if (NULL != warningId)
    {
        mxArray *mxCommandResponse = NULL, *mxException = NULL;
        mxArray *args[2];
        /* warning('query', warningId); */
        args[0] = mxCreateString("query");
        args[1] = mxCreateString(warningId);
        mxException = mexCallMATLABWithTrap(1,&mxCommandResponse,2,args,"warning");
        if (NULL == mxException && NULL != mxCommandResponse)
        {
            if (mxIsStruct(mxCommandResponse))
            {
                const mxArray* state_field = mxGetField(mxCommandResponse, 0, "state");
                if (mxIsChar(state_field))
                {
                    char state_value[8] = {0};
                    enabled = (0 == mxGetString(state_field, state_value, 8)) &&
                              (0 == strcmp(state_value,"on"));
                }
            }
            mxDestroyArray(mxCommandResponse);
        }
        else
        {
            /* 'warning' returned with error */
            mxDestroyArray(mxException);
        }
        mxDestroyArray(args[0]);
        mxDestroyArray(args[1]);
    }
    return enabled;
}
</pre>
<p>This approach is slow, but works fine in most standard situations. See the bottom of this post for a usage example.<br />
However, this approach has an important drawback – we should be careful with recursive calls to the Matlab interpreter (<code>Matlab -> MEX -> Matlab</code>) and with <a href="http://www.advanpix.com/2016/02/14/short-and-informative-error-messages-from-mex/" rel="nofollow" target="_blank">handling Matlab errors in MEX</a>. It is safe only if we use identical standard libraries and compiler to build both MEX and Matlab.<br />
In other cases, for example when MEX is targeted to work with different versions of Matlab, or was built with a different standard library and compiler, etc. – cross boundary handling of errors (which are just C++ exceptions) might lead to unpredictable results, most likely segfaults.</p>
<h3 id="utGetWarningStatus">Using utGetWarningStatus (undocumented)</h3>
<p>To avoid all the overhead of calling Matlab interpreter and unsafe error handling, we can use some undocumented internal Matlab functions:</p>
<pre lang="cpp">
/* Link with libut library to pick-up undocumented functions: */
extern "C" void* utGetWarningManagerContext(void);
extern "C" bool  utIsValidMessageIdentifier(const char *warningId);
extern "C" bool  utGetWarningStatus(void* context, const char *warningId);
/*
   Returns true if warning with warningId enabled
   Matlab versions supported/tested: R2008b - R2016b
*/
bool mxIsWarningEnabled(const char *warningId)
{
    bool enabled = true;
    if (NULL != warningId && utIsValidMessageIdentifier(warningId))
    {
        void* context = utGetWarningManagerContext();
        enabled = (NULL != context) && utGetWarningStatus(context, warningId);
    }
    return enabled;
}
</pre>
<p>Now the code is clean, fast and safe – we bypass the interpreter and work directly with Matlab kernel. All the undocumented functions involved are present in Matlab for at least 10 years and do simple logical checks under the hood.<br />
The standard function <code><a href="https://www.mathworks.com/help/matlab/apiref/mexwarnmsgidandtxt.html" rel="nofollow" target="_blank">mexWarnMsgIdAndTxt</a></code> uses similar code to check if it should display the warning or just suppress it, and that code remains unchanged since R2008b. This is a good indication of code stability and makes us believe that it will not be changed in future versions of Matlab.<br />
For both workarounds, usage is simple:</p>
<pre lang="cpp">
if (mxIsWarningEnabled("Matlab:nearlySingularMatrix"))
{
   /* compute rcond */
}
else
{
   /* do something else */
}
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex">Checking status of warning messages in MEX</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/better-mex-error-messages" rel="bookmark" title="Better MEX error messages">Better MEX error messages </a> <small>The default clunky and release-incompatible MEX error messages can be improved using a simple hack. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-text" rel="bookmark" title="Setting status-bar text">Setting status-bar text </a> <small>The Matlab desktop and figure windows have a usable statusbar which can only be set using undocumented methods. This post shows how to set the status-bar text....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-components" rel="bookmark" title="Setting status-bar components">Setting status-bar components </a> <small>Matlab status-bars are Java containers in which we can add GUI controls such as progress-bars, not just simple text labels...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sending-email-text-messages-from-matlab" rel="bookmark" title="Sending email/text messages from Matlab">Sending email/text messages from Matlab </a> <small>Sending emails and SMS (text) messages from Matlab is easy, once you know a few quirks....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>A few parfor tips</title>
		<link>https://undocumentedmatlab.com/articles/a-few-parfor-tips?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=a-few-parfor-tips</link>
					<comments>https://undocumentedmatlab.com/articles/a-few-parfor-tips#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 06 Jul 2016 16:29:21 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Public presentation]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6516</guid>

					<description><![CDATA[<p>The parfor (parallel for) loops  can be made faster using a few simple tips. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/a-few-parfor-tips">A few parfor tips</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/quirks-with-parfor-vs-for" rel="bookmark" title="Quirks with parfor vs. for">Quirks with parfor vs. for </a> <small>Parallelizing loops with Matlab's parfor might generate unexpected results. Users beware! ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance" rel="bookmark" title="Tips for accelerating Matlab performance">Tips for accelerating Matlab performance </a> <small>My article on "Tips for Accelerating MATLAB Performance" was recently featured in the September 2017 Matlab newsletter digest. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/some-performance-tuning-tips" rel="bookmark" title="Some Matlab performance-tuning tips">Some Matlab performance-tuning tips </a> <small>Matlab can be made to run much faster using some simple optimization techniques. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><figure style="width: 500px" class="wp-caption alignright"><a href="http://www.mathworks.com/videos/creating-professional-quality-applications-with-matlab-120623.html" rel="nofollow" target="_blank"><img decoding="async" alt="Matlab Expo 2016 keynote presentation" src="https://undocumentedmatlab.com/images/DE-Expo-2016a.jpg" title="Matlab Expo 2016 keynote presentation" width="500" height="281" /></a><figcaption class="wp-caption-text">Matlab Expo 2016 keynote presentation</figcaption></figure> A few days ago, MathWorks uploaded a video recording of my recent <a href="/articles/upcoming-public-matlab-presentations" target="_blank">keynote presentation</a> at the Matlab Expo 2016 in Munich, Germany. During the presentation, I skimmed over a few tips for improving performance of parallel-processing (<i><b>parfor</b></i>) loops. In today&#8217;s post I plan to expand on these tips, as well as provide a few others that for lack of space and time I did not mention in the presentation.<br />
The overall effect can be dramatic: The performance (speed) difference between a sub-optimal and optimized <i><b>parfor</b></i>&#8216;ed code can be up to a full order of magnitude, depending on the specific situation. Naturally, to use any of today&#8217;s tips, you need to have MathWorks&#8217; Parallel Computing Toolbox (PCT).<br />
Before diving into the technical details, let me say that MathWorks has extensive documentation on PCT. In today&#8217;s post I will try not to reiterate the official tips, but rather those that I have not found mentioned elsewhere, and/or are not well-known (my apologies in advance if I missed an official mention of one or more of the following). Furthermore, I limit myself only to <i><b>parfor</b></i> in this post: much can be said about <i><b>spmd</b></i>, GPU and other parallel constructs, but not today.<br />
<span id="more-6516"></span></p>
<h3 id="numCores"><i>parpool(numCores)</i></h3>
<p>The first tip is to not [always] use the default number of workers created by <i><b>parpool</b></i> (or <i><b>matlabpool</b></i> in R2013a or earlier). By default, Matlab creates as many workers as logical CPU cores. On Intel CPUs, the OS reports two logical cores per each physical core due to hyper-threading, for a total of 4 workers on a dual-core machine. However, in many situations, hyperthreading does not improve the performance of a program and may even degrade it (I deliberately wish to avoid the heated debate over this: you can find endless discussions about it online and decide for yourself). Coupled with the non-negligible overhead of starting, coordinating and communicating with twice as many Matlab instances (workers are headless [=GUI-less] Matlab processes after all), we reach a conclusion that it may actually be better in many cases to use only as many workers as physical (not logical) cores.<br />
I know the documentation and configuration panel seem to imply that <i><b>parpool</b></i> uses the number of physical cores by default, but in my tests I have seen otherwise (namely, logical cores). Maybe this is system-dependent, and maybe there is a switch somewhere that controls this, I don&#8217;t know. I just know that in many cases I found it beneficial to <i>reduce</i> the number of workers to the actual number of physical cores:</p>
<pre lang="matlab">
p = parpool;     % use as many workers as logical CPUs (4 on my poor laptop...)
p = parpool(2);  % use only 2 parallel workers
</pre>
<p>Of course, this can vary greatly across programs and platforms, so you should test carefully on your specific setup. I suspect that for the majority of Matlab programs it would turn out that using the number of physical cores is better.<br />
It would of course be better to dynamically retrieve the number of physical cores, rather than hard-coding a constant value (number of workers) into our program. We can get this value in Matlab using the undocumented <i><b>feature(&#8216;numcores&#8217;)</b></i> function:</p>
<pre lang="matlab">
numCores = feature('numcores');
p = parpool(numCores);
</pre>
<p>Running <i><b>feature(&#8216;numcores&#8217;)</b></i> without assigning its output displays some general debugging information:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; feature(<span style="color:#A020F0;">'numcores'</span>)
MATLAB detected: 2 physical cores.
MATLAB detected: 4 logical cores.
MATLAB was assigned: 4 logical cores by the OS.
MATLAB is using: 2 logical cores.
MATLAB is not using all logical cores because hyper-threading is enabled.
ans =
     2
</pre>
</div>
</div>
<p>Naturally, this specific tip is equally valid for both <i><b>parfor</b></i> loops and <i><b>spmd</b></i> blocks, since both of them use the pool of workers started by <i><b>parpool</b></i>.</p>
<h3 id="multi-code">Running separate code in parfor loops</h3>
<p>The conventional wisdom is that <i><b>parfor</b></i> loops (and loops in general) can only run a single code segment over all its iterations. Of course, we can always use conditional constructs (such as <i><b>if</b></i> or <i><b>switch</b></i>) based on the data. But what if we wanted some workers to run a different code path than the other workers? In <i><b>spmd</b></i> blocks we could use a conditional based on the <i><b>labindex</b></i> value, but unfortunately <i><b>labindex</b></i> is always set to the same value 1 within <i><b>parfor</b></i> loops. So how can we let worker A run a different code path than worker B?<br />
An obvious answer is to create a <i><b>parfor</b></i> loop having as many elements as there are separate code paths, and use a <i><b>switch-case</b></i> mechanism to run the separate paths, as follows:</p>
<pre lang="matlab">
% Naive implementation example - do NOT use!
parfor idx = 1 : 3
   switch idx
      case 1,  result{1} = fun1(data1, data2);
      case 2,  result{2} = fun2(data3, data4, data5);
      case 3,  result{3} = fun3(data6);
   end
end
</pre>
<p>There are several problems with this naive implementation. First, it unnecessarily broadcasts all the input data to all workers (more about this issue below). Secondly, it appears clunky and too verbose. A very nice extension of this mechanism, <a href="http://stackoverflow.com/questions/4495000/multi-threading-in-matlab" rel="nofollow" target="_blank">posted by StackOverflow heavyweight Jonas</a>, uses indexed arrays of function handles and input args, thereby solving both problems:</p>
<pre lang="matlab">
funcList = {@fun1, @fun2, @fun3};
dataList = {data1, data2, data3};  %# or pass file names
parfor idx = 1 : length(funcList)
    result{idx} = funcList{idx}(dataList{idx});
end
</pre>
<h3 id="broadcast">Reduce the amount of broadcast data</h3>
<p>It is often easy, <i>too</i>-easy, to convert <i><b>for</b></i> loops into <i><b>parfor</b></i> loops. In many cases, all we need to do is to add the &#8220;par&#8221; prefix to the <i><b>for</b></i> keyword and we&#8217;re done (assuming we have no incompatibly-used variables that should be converted into sliced variables etc.). This transformation was intentionally made simple by MathWorks (which is great!). On the other hand, it also hides a lot under the hood. One of the things that is often overlooked in such simple loop transformations is that a large part of the data used within the loop needs to be copied (<i>broadcast</i>) to each of the workers separately. This means that each of the data items needs to be serialized (i.e., copied in memory), packaged, communicated to and accepted by each of the workers. This can mean a lot of memory, networking bandwidth and time-consuming. It can even mean thrashing to hard-disk in case the number of workers times the amount of transferred data exceeds the available RAM. For example, if we have 10GB available RAM and try to communicate 3GB to 4 workers, we will not have enough RAM and the OS will start swapping to hard-disk. This will kill performance and Matlab will appear &#8220;hung&#8221; and will need to be hard-killed.<br />
You might think that it would be very difficult to reach the RAM limit, but in fact it can be far too easy when you consider the multiplication by the number of workers, and the fact that each worker uses 1+GB of memory just for its MATLAB process, even before the data, and all this in addition to the parent (client) Matlab process. That&#8217;s a lot of GBs flying around&#8230;<br />
Moreover, it&#8217;s enough for one small part of a Matlab struct or array to be used within the <i><b>parfor</b></i> loop for the entire Matlab construct to be broadcast to all workers. For example, a very common use-case is to store program data, both raw and processed, within a simple Matlab struct. Let&#8217;s say that we have <code>data.raw</code> and <code>data.processed</code> and within the loop we only need <code>data.processed</code> &#8211; the entire <code>data</code> variable (which might include many GBs due to the raw data) is broadcast, although the loop&#8217;s code only needs <code>data.processed</code>. In such cases, it makes sense to separate the broadcast data into standalone variables, and only use them within the loop:</p>
<pre lang="matlab">
data.raw = ...
data.processed = ...
% Inefficient variant:
parfor idx = 1 : N
   % do something with data.processed
end
% This is better:
processedData = data.processed;
parfor idx = 1 : N
   % do something with processedData
end
</pre>
<p>Moreover, if you can convert a broadcast variable into a sliced one, this would be even better: in this case each worker will only be communicated its small share (&#8220;slice&#8221;) of the entire data, rather than a full copy of the entire data.<br />
All this would of course be much simpler if Matlab&#8217;s computational engine was multi-threaded, since then PCT could be implemented using lightweight threads rather than heavyweight processes. The memory and communication overheads would then be drastically reduced and performance would improve significantly. Unfortunately, Matlab&#8217;s computational engine is [still] single-threaded, preventing this. Hopefully Matlab&#8217;s new engine (which debuted in R2015b) will enable true multithreading at some future release. PCT will still need to retain an option of using headless worker processes to run on multiple machines (i.e., distributed/grid/cloud computing), but single-machine parallelization should employ multithreading instead.<br />
Additional speedup tips can be found in my book &#8220;<i><a href="/books/matlab-performance" target="_blank">Accelerating MATLAB Performance</a></i>&#8220;.<br />
Do you have some other important <i><b>parfor</b></i> tips that you found useful? If so, please post them in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/a-few-parfor-tips">A few parfor tips</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/quirks-with-parfor-vs-for" rel="bookmark" title="Quirks with parfor vs. for">Quirks with parfor vs. for </a> <small>Parallelizing loops with Matlab's parfor might generate unexpected results. Users beware! ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance" rel="bookmark" title="Tips for accelerating Matlab performance">Tips for accelerating Matlab performance </a> <small>My article on "Tips for Accelerating MATLAB Performance" was recently featured in the September 2017 Matlab newsletter digest. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/some-performance-tuning-tips" rel="bookmark" title="Some Matlab performance-tuning tips">Some Matlab performance-tuning tips </a> <small>Matlab can be made to run much faster using some simple optimization techniques. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/a-few-parfor-tips/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>MEX ctrl-c interrupt</title>
		<link>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mex-ctrl-c-interrupt</link>
					<comments>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 15 Jun 2016 17:00:40 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pavel Holoborodko]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6454</guid>

					<description><![CDATA[<p>An undocumented MEX function can help interrupt running MEX functions. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt">MEX ctrl-c interrupt</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite" rel="bookmark" title="Faster csvwrite/dlmwrite">Faster csvwrite/dlmwrite </a> <small>The speed of the builtin csvwrite, dlmwrite functions can be improved dramatically. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api" rel="bookmark" title="Undocumented Matlab MEX API">Undocumented Matlab MEX API </a> <small>Matlab's MEX API contains numerous undocumented functions, that can be extremely useful. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data" rel="bookmark" title="Serializing/deserializing Matlab data">Serializing/deserializing Matlab data </a> <small>Matlab does not provide a documented manner to serialize data into a byte stream, but we can do this with some undocumented functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I recently became aware of a <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/" rel="nofollow" target="_blank">very nice hack</a> by <a href="http://math.ucla.edu/~wotaoyin" rel="nofollow" target="_blank">Wotao Yin</a> (while at Rice in 2010; currently teaching at UCLA). The core problem is that unlike m-files that can be interrupted in mid-run using ctrl-c, MEX functions cannot be interrupted in the same way. Well, not officially, that is.<br />
Interrupts are very important for long-running user-facing operations. They can even benefit performance by avoiding the need to periodically poll some external state. Interrupts are registered asynchronously, and the program can query the interrupt buffer at its convenience, in special locations of its code, and/or at specific times depending on the required responsiveness.<br />
Yin reported that the <i>libut</i> library that ships with Matlab contain a large set of undocumented functions, including <code>utIsInterruptPending()</code> that can be used to detect ctrl-c interrupt events. The original report of this feature seems to be by Matlab old hand <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/37732#95811" rel="nofollow" target="_blank">Peter Boettcher back in 2002</a> (with a <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/326230" rel="nofollow" target="_blank">Fortran wrapper</a> reported in 2013). The importance of Yin&#8217;s post is that he clearly explained the use of this feature, with detailed coding and compilation instructions. Except for Peter&#8217;s original report, Yin&#8217;s post and the Fortran wrapper, precious few mentions can be found online (oddly enough, yours truly <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/247651#638201" rel="nofollow" target="_blank">mentioned it</a> in the very same CSSM newsletter post in which I outed this blog back in 2009). Apparently, this feature <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/37732" rel="nofollow" target="_blank">was supposed to have been made documented in R12.1</a>, but for some reason it was not and people just moved on and forgot about it.<br />
<span id="more-6454"></span><br />
The relevant functions seem to be:</p>
<pre lang="cpp">
// Most important functions (C):
bool utIsInterruptEnabled(void)
bool utIsInterruptPending(void)
bool utWasInterruptHandled(void)
bool utSetInterruptHandled(bool)
bool utSetInterruptEnabled(bool)
bool utSetInterruptPending(bool)
// Related functions (C, signature unknown):
? utHandlePendingInterrupt(?)
? utRestoreInterruptEnabled(?)
? utLongjmpIfInterruptPending(?)
// utInterruptMode class (C++):
utInterruptMode::utInterruptMode(enum utInterruptMode::Mode)  // constructor
utInterruptMode::~utInterruptMode(void)  // destructor
bool utInterruptMode::isInterruptEnabled(void)
enum utInterruptMode::Mode utInterruptMode::CurrentMode
enum utInterruptMode::Mode utInterruptMode::GetCurrentMode(void)
enum utInterruptMode::Mode utInterruptMode::GetOriginalMode(void)
enum utInterruptMode::Mode utInterruptMode::SetMode(enum utInterruptMode::Mode)
// utInterruptState class (C++):
class utInterruptState::AtomicPendingFlags utInterruptState::flags_pending
void utInterruptState::HandlePeekMsgPending(void)
bool utInterruptState::HandlePendingInterrupt(void)
bool utInterruptState::interrupt_handled
bool utInterruptState::IsInterruptPending(void)
bool utInterruptState::IsPauseMsgPending(void)
class utInterruptState & utInterruptState::operator=(class utInterruptState const &)
void utInterruptState::PeekMessageIfPending(void)
bool utInterruptState::SetInterruptHandled(bool)
bool utInterruptState::SetInterruptPending(bool)
bool utInterruptState::SetIqmInterruptPending(bool)
bool utInterruptState::SetPauseMsgPending(bool)
bool utInterruptState::SetPeekMsgPending(bool)
void utInterruptState::ThrowIfInterruptPending(void)
bool utInterruptState::WasInterruptHandled(void)
unsigned int const utInterruptState::FLAG_PENDING_CTRLC
unsigned int const utInterruptState::FLAG_PENDING_INTERRUPT_MASK
unsigned int const utInterruptState::FLAG_PENDING_IQM_INTERRUPT
unsigned int const utInterruptState::FLAG_PENDING_PAUSE
unsigned int const utInterruptState::FLAG_PENDING_PEEKMSG
</pre>
<p>Of all these functions, we can make do with just <code>utIsInterruptPending</code>, as <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/" rel="nofollow" target="_blank">shown</a> by Yin (complete with compilation instructions):</p>
<pre lang="cpp">
/* A demo of Ctrl-C detection in mex-file by Wotao Yin. Jan 29, 2010. */
#include "mex.h"
#if defined (_WIN32)
    #include <windows.h>
#elif defined (__linux__)
    #include <unistd.h>
#endif
#ifdef __cplusplus
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int count = 0;
    while(1) {
        #if defined(_WIN32)
            Sleep(1000);        /* Sleep one second */
        #elif defined(__linux__)
            usleep(1000*1000);  /* Sleep one second */
        #endif
        mexPrintf("Count = %d\n", count++);  /* print count and increase it by 1 */
        mexEvalString("drawnow;");           /* flush screen output */
        if (utIsInterruptPending()) {        /* check for a Ctrl-C event */
            mexPrintf("Ctrl-C Detected. END\n\n");
            return;
        }
        if (count == 10) {
            mexPrintf("Count Reached 10. END\n\n");
            return;
        }
    }
}
</pre>
<p>After returning to Matlab, the Ctrl-C event will stop the execution of the caller function(s). However, sometimes we would like to keep the partial calculation, for example if the calculation can later be resumed from the point of interruption. It&#8217;s not possible to save partial result using only the utIsInterruptPending() function. However, it is possible to reset the interrupt state so that Matlab will not stop the execution after returning control from the mex function, and the caller function can get and use the partial calculation. The magic is done using another undocumented libut function named ​<i>utSetInterruptPending()</i>. A short example is included below (provided by Zvi Devir):</p>
<pre lang="cpp" highlight="4,14">
// Import libut functions
#pragma comment(lib, "libut.lib")
extern "C" bool utIsInterruptPending();
extern "C" bool utSetInterruptPending(bool);
// Run calculation divided into steps
int n;
for (n = 0; n < count; n++) {
	// some expensive calculation
	a_long_calculation(..., n);
	if (utIsInterruptPending()) {		// check for a Ctrl-C event
		mexPrintf("Ctrl-C detected [%d/%d].\n\n", n, count);
		utSetInterruptPending(false);	// Got it... consume event
		break;
	}
}
// Write back partial or full calculation
...
</pre>
<p>An elaboration of the idea of Ctrl-C detection was <a href="https://groups.google.com/d/msg/gerardus-users/m3rzaxHnmMM/eVo6K2WZxvYJ" rel="nofollow" target="_blank">created</a> by <a href="http://www.cs.ox.ac.uk/people/ramon.caserocanas/" rel="nofollow" target="_blank">Ramon Casero</a> (Oxford) for the <a href="https://github.com/rcasero/gerardus" rel="nofollow" target="_blank">Gerardus project</a>. Ramon wrapped Yin's code in C/C++ <code>#define</code> to create an easy-to-use pre-processor function <code>ctrlcCheckPoint(fileName,lineNumber)</code>:</p>
<pre lang="cpp">
...
ctrlcCheckPoint(__FILE__, __LINE__);  // exit if user pressed Ctrl+C
...
</pre>
<p>Here's the code for the preprocessor header file (<a href="https://github.com/rcasero/gerardus/blob/master/matlab/GerardusCommon.h" rel="nofollow" target="_blank"><i>GerardusCommon.h</i></a>) that #defines <code>ctrlcCheckPoint()</code> (naturally, the <code>__FILE__</code> and <code>__LINE__</code> parts could also be made part of the #define, for even simpler usage):</p>
<pre lang="cpp">
 /*
  * Author: Ramon Casero <rcasero@gmail.com>
  * Copyright © 2011-2013 University of Oxford
  * Version: 0.10.2
  *
  * University of Oxford means the Chancellor, Masters and Scholars of
  * the University of Oxford, having an administrative office at
  * Wellington Square, Oxford OX1 2JD, UK.
  *
  * This file is part of Gerardus.
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details. The offer of this
  * program under the terms of the License is subject to the License
  * being interpreted in accordance with English Law and subject to any
  * action against the University of Oxford being under the jurisdiction
  * of the English Courts.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see
  * <http://www.gnu.org/licenses/>.
  */
#ifndef GERARDUSCOMMON_H
#define GERARDUSCOMMON_H
/* mex headers */
#include <mex.h>
/* C++ headers */
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
/* ITK headers */
#include "itkOffset.h"
/*
 * utIsInterruptPending(): "undocumented MATLAB API implemented in
 * libut.so, libut.dll, and included in the import library
 * libut.lib. To use utIsInterruptPending in a mex-file, one must
 * manually declare bool utIsInterruptPending() because this function
 * is not included in any header files shipped with MATLAB. Since
 * libut.lib, by default, is not linked by mex, one must explicitly
 * tell mex to use libut.lib." -- Wotao Yin,
 * http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/
 *
 */
#ifdef __cplusplus
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif
/*
 * ctrlcCheckPoint(): function to check whether the user has pressed
 * Ctrl+C, and if so, terminate execution returning an error message
 * with a hyperlink to the offending function's help, and a hyperlink
 * to the line in the source code file this function was called from
 *
 * It is implemented as a C++ macro to check for the CTRL+C flag, and
 * a call to function ctrlcErrMsgTxt() inside, to throw the error. The
 * reason is that if ctrlcCheckPoint() were a function instead of a
 * macro, this would introduce a function call at every iteration of
 * the loop, which is very expensive. But then we don't want to put
 * the whole error message part inside a macro, it's bug-prone and bad
 * programming practice. And once the CTRL+C has been detected,
 * whether the error message is generated a bit faster or not is not
 * important.
 *
 * In practice, to use this function put a call like this e.g. inside
 * loops that may take for a very long time:
 *
 *    // exit if user pressed Ctrl+C
 *    ctrlcCheckPoint(__FILE__, __LINE__);
 *
 * sourceFile: full path and name of the C++ file that calls this
 *             function. This should usually be the preprocessor
 *             directive __FILE__
 *
 * lineNumber: line number where this function is called from. This
 *             should usually be the preprocessor directive __LINE__
 *
 */
inline
void ctrlcErrMsgTxt(std::string sourceFile, int lineNumber) {
  // run from here the following code in the Matlab side:
  //
  // >> path = mfilename('fullpath')
  //
  // this provides the full path and function name of the function
  // that called ctrlcCheckPoint()
  int nlhs = 1; // number of output arguments we expect
  mxArray *plhs[1]; // to store the output argument
  int nrhs = 1; // number of input arguments we are going to pass
  mxArray *prhs[1]; // to store the input argument we are going to pass
  prhs[0] = mxCreateString("fullpath"); // input argument to pass
  if (mexCallMATLAB(nlhs, plhs, nrhs, prhs, "mfilename")) { // run mfilename('fullpath')
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned error");
  }
  if (plhs == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned NULL array of outputs");
  }
  if (plhs[0] == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned NULL output instead of valid path");
  }
  // get full path to current function, including function's name
  // (without the file extension)
  char *pathAndName = mxArrayToString(plhs[0]);
  if (pathAndName == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') output cannot be converted to string");
  }
  // for some reason, using mexErrMsgTxt() to give this output
  // doesn't work. Instead, we have to give the output to the
  // standar error, and then call mexErrMsgTxt() to terminate
  // execution of the program
  std::cerr << "Operation terminated by user during "
	    << "<a href=\"matlab:helpUtils.errorDocCallback('"
	    << mexFunctionName()
	    << "', '" << pathAndName << ".m', " << lineNumber << ")\">"
	    << mexFunctionName()
	    << "</a> (<a href=\"matlab:opentoline('"
	    << sourceFile
	    << "'," << lineNumber << ",0)\">line " << lineNumber
	    << "</a>)"
	    << std::endl;
  mexErrMsgTxt("");
}
#define ctrlcCheckPoint(sourceFile, lineNumber)		\
  if (utIsInterruptPending()) {				\
    ctrlcErrMsgTxt(sourceFile, lineNumber);		\
  }
</pre>
<p>This feature has remained as-is since at least 2002 (when Peter first reported it), and apparently works to this day. Why then did I categorize this as "High risk for breaking in a future Matlab versions"? The reason is that internal undocumented MEX functions are prone to break in new Matlab releases (<a href="/articles/serializing-deserializing-matlab-data" target="_blank">example</a>). Hopefully my report today will prompt MathWorks to make this feature documented, rather than to remove it from a future release 🙂<br />
By the way, if anyone knows any use for the other interrupt-related functions in <i>libut</i> that I listed above, and/or the missing signatures, please leave a note below and I will update here accordingly.<br />
<b><u>Addendum July 2, 2016:</u></b> Pavel Holoborodko <a href="http://www.advanpix.com/2016/07/02/devnotes-3-proper-handling-of-ctrl-c-in-mex-module" rel="nofollow" target="_blank">just posted</a> an asynchronous version of this mechanism, which is an improvement of the synchronous code above. Pavel uses a separate Windows thread to check the Ctrl-C interrupt state. Readers can extend this idea to use threads for other asynchronous (multi-threaded) computations or I/O. In chapter 7 of my book "<a href="/books/matlab-java" rel="nofollow" target="_blank">Accelerating MATLAB Performance</a>" I explain how we can use Posix threads (pthreads) or OpenMP threads for similar multithreading in MEX (unlike Windows threads, pthreads and OpenMP are cross platform). Users can also use other multithreading solutions, such as the open-source Boost library (bundled with Matlab) or Intel's commercial TBB.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt">MEX ctrl-c interrupt</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite" rel="bookmark" title="Faster csvwrite/dlmwrite">Faster csvwrite/dlmwrite </a> <small>The speed of the builtin csvwrite, dlmwrite functions can be improved dramatically. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api" rel="bookmark" title="Undocumented Matlab MEX API">Undocumented Matlab MEX API </a> <small>Matlab's MEX API contains numerous undocumented functions, that can be extremely useful. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data" rel="bookmark" title="Serializing/deserializing Matlab data">Serializing/deserializing Matlab data </a> <small>Matlab does not provide a documented manner to serialize data into a byte stream, but we can do this with some undocumented functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Enabling user callbacks during zoom/pan</title>
		<link>https://undocumentedmatlab.com/articles/enabling-user-callbacks-during-zoom-pan?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=enabling-user-callbacks-during-zoom-pan</link>
					<comments>https://undocumentedmatlab.com/articles/enabling-user-callbacks-during-zoom-pan#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 28 Oct 2015 12:42:03 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[scribe]]></category>
		<category><![CDATA[uimode]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6043</guid>

					<description><![CDATA[<p>Matlab zoom, pan and rotate3d modes hijack the user's figure callbacks, but this can be overridden. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/enabling-user-callbacks-during-zoom-pan">Enabling user callbacks during zoom/pan</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/user-defined-tab-completions-take-2" rel="bookmark" title="User-defined tab completions &#8211; take 2">User-defined tab completions &#8211; take 2 </a> <small>Matlab has changed the mechanism that enables user-defined tab-completion of function inputs. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/determining-axes-zoom-state" rel="bookmark" title="Determining axes zoom state">Determining axes zoom state </a> <small>The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>An annoying side-effect of Matlab figure uimodes (zoom, pan and rotate3d) is that they disable the user&#8217;s figure-wide callbacks (<b>KeyPressFcn</b>, <b>KeyReleaseFcn</b>, <b>WindowKeyPressFcn</b>, <b>WindowKeyReleaseFcn</b>, <b>WindowButtonUpFcn</b>, <b>WindowButtonDownFcn</b> and <b>WindowScrollWheelFcn</b>). In most cases, users will indeed expect the mouse and keyboard behavior to change when these modes are active (selecting a zoom region with the mouse for instance). However, in certain cases we may need to retain our custom callback behavior even when the modes are active. This is particularly relevant for the keyboard callbacks, which are not typically used to control the modes and yet may be very important for our figure&#8217;s interactive functionality. Unfortunately, Matlab&#8217;s mode manager installs property listeners that prevent users from modifying these callback when any mode is active:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; hFig=<span style="color: #0000FF;">figure</span>; <span style="color: #0000FF;">plot</span><span style="color: #080;">(</span><span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">5</span><span style="color: #080;">)</span>; <span style="color: #0000FF;">zoom</span> <span style="color:#A020F0;">on</span>
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">(</span>hFig, <span style="color:#A020F0;">'KeyPressFcn'</span>, <span style="color: #F0F;">@</span>myKeyPressCallback<span style="color: #080;">)</span>
<span style="color: orange;">Warning: Setting the "KeyPressFcn" property is not permitted while this mode is active.
(Type "warning off MATLAB:modes:mode:InvalidPropertySet" to suppress this warning.)
&nbsp;
&gt; In matlab.uitools.internal.uimodemanager&gt;localModeWarn (line 211)
  In matlab.uitools.internaluimodemanager&gt;@(obj,evd)(localModeWarn(obj,evd,hThis)) (line 86)</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">get</span><span style="color: #080;">(</span>hFig, <span style="color:#A020F0;">'KeyPressFcn'</span><span style="color: #080;">)</span>  <span style="color: #228B22;">% the KeyPressFcn callback set by the mode manager</span>
ans =
    <span style="color: #F0F;">@</span>localModeKeyPressFcn
    <span style="color: #080;">[</span>1x1 matlab.<span style="">uitools</span>.<span style="">internal</span>.<span style="">uimode</span><span style="color: #080;">]</span>
    <span style="color: #080;">{</span>1x2 cell                          <span style="color: #080;">}</span></pre>
</div>
</div>
<p>The question of how to override this limitation has appeared multiple times over the years in the CSSM newsgroup (<a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/235114">example1</a>, <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/283529">example2</a>) and the Answers forum, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/251339-re-enable-keypress-capture-in-pan-or-zoom-mode">most recently yesterday</a>, so I decided to dedicate today&#8217;s article to this issue.<br />
<span id="more-6043"></span><br />
In Matlab GUI, a &#8220;mode&#8221; (aka <i>uimode</i>) is a set of defined behaviors that may be set for any figure window and activated/deactivated via the figure&#8217;s menu, toolbar or programmatically. Examples of predefined modes are plot edit, zoom, pan, rotate3d and data-cursor. Only one mode can be active in a figure at any one time – this is managed via a figure&#8217;s <code>ModeManager</code>. Activating a figure mode automatically deactivates any other active mode, as can be seen when switching between plot edit, zoom, pan, rotate3d and data-cursor modes.<br />
This mode manager is implemented in the <i><b>uimodemanager</b></i> class in <i>%matlabroot%/toolbox/matlab/uitools/+matlab/+uitools/internal/@uimodemanager/uimodemanager.m</i> and its sibling functions in the same folder. Until recently it used to be implemented in Matlab&#8217;s old class system, but was recently converted to the new MCOS (<i><b>classdef</b></i>) format, without an apparent major overhaul of the underlying logic (which I think is a pity, but refactoring naturally has lower priority than fixing bugs or adding new functionality).<br />
Anyway, until HG2 (R2014b), the solution for bypassing the mode-manager&#8217;s callbacks hijacking was as follows (credit: Walter Roberson):</p>
<pre lang='matlab'>
% This will only work in HG1 (R2014a or earlier)
hManager = uigetmodemanager(hFig);
set(hManager.WindowListenerHandles, 'Enable', 'off');
set(hFig, 'WindowKeyPressFcn', []);
set(hFig, 'KeyPressFcn', @myKeyPressCallback);
</pre>
<p>In HG2 (R2014b), the interface of <b>WindowListenerHandles</b> changed and the above code no longer works:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">(</span>hManager.<span style="">WindowListenerHandles</span>, <span style="color:#A020F0;">'Enable'</span>, <span style="color:#A020F0;">'off'</span><span style="color: #080;">)</span>;
<span style="color: #FF0000;">Error using set
Cannot find 'set' method for event.proplistener class</span>.</pre>
</div>
</div>
<p>Luckily, in MathWorks&#8217; refactoring to MCOS, the property name <b>WindowListenerHandles</b> was not changed, nor its status as a public read-only hidden property. So we can still access it directly. The only thing that changed is its meta-properties, and this is due not to any change in the mode-manager&#8217;s code, but rather to a much more general change in the implementation of the <i><b>event.proplistener</b></i> class:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; hManager.<span style="">WindowListenerHandles</span><span style="color: #080;">(</span><span style="color: #33f;">1</span><span style="color: #080;">)</span>
ans =
  <span style="color: #0000FF;text-decoration: underline;">proplistener</span> with properties:
&nbsp;
       Object<span style="color: #F0F;">:</span> <span style="color: #080;">{</span><span style="color: #080;">[</span>1x1 Figure<span style="color: #080;">]</span><span style="color: #080;">}</span>
       Source<span style="color: #F0F;">:</span> <span style="color: #080;">{</span>7x1 cell<span style="color: #080;">}</span>
    EventName<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'PreSet'</span>
     Callback<span style="color: #F0F;">:</span> <span style="color: #F0F;">@</span><span style="color: #080;">(</span>obj,evd<span style="color: #080;">)</span><span style="color: #080;">(</span>localModeWarn<span style="color: #080;">(</span>obj,evd,hThis<span style="color: #080;">)</span><span style="color: #080;">)</span>
      Enabled<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
    Recursive<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span></pre>
</div>
</div>
<p>In the new <i><b>proplistener</b></i>, the <b>Enabled</b> meta-property is now a boolean (logical) value rather than a string, and was renamed <b>Enabled</b> in place of the original <b>Enable</b>. Also, the new <i><b>proplistener</b></i> doesn&#8217;t inherit <i><b>hgsetget</b></i>, so it does not have <i><b>set</b></i> and <i><b>get</b></i> methods, which is why we got an error above; instead, we should use direct dot-notation.<br />
In summary, the code that should now be used, and is backward compatible with old HG1 releases as well as new HG2 releases, is as follows:</p>
<pre lang='matlab'>
% This should work in both HG1 and HG2:
hManager = uigetmodemanager(hFig);
try
    set(hManager.WindowListenerHandles, 'Enable', 'off');  % HG1
catch
    [hManager.WindowListenerHandles.Enabled] = deal(false);  % HG2
end
set(hFig, 'WindowKeyPressFcn', []);
set(hFig, 'KeyPressFcn', @myKeyPressCallback);
</pre>
<p>During an active mode, the mode-manager disables user-configured mouse and keyboard callbacks, in order to prevent interference with the mode&#8217;s functionality. For example, mouse clicking during zoom mode has a very specific meaning, and user-configured callbacks might interfere with it. Understanding this and taking the proper precautions (for example: chaining the default mode&#8217;s callback at the beginning or end of our own callback), we can override this default behavior, as shown above.<br />
Note that the entire mechanism of mode-manager (and the related <a target="_blank" href="/articles/tag/scribe">scribe objects</a>) is undocumented and might change without notice in future Matlab releases. We were fortunate in the current case that the change was small enough that a simple workaround could be found, but this may possibly not be the case next time around. It&#8217;s impossible to guess when such features will eventually break: it might happen in the very next release, or 20 years in the future. Since there are no real alternatives, we have little choice other than to use these features, and document the risk (the fact that they use undocumented aspects). In your documentation/comments, add a link back here so that if something ever breaks you&#8217;d be able to check if I posted any fix or workaround.<br />
For the sake of completeness, here is a listing of the accessible properties (regular and hidden) of both the mode-manager as well as the zoom uimode, in R2015b:</p>
<pre lang='matlab'>
>> warning('off', 'MATLAB:structOnObject');  % suppress warning about using structs (yes we know it's not good for us...)
>> struct(hManager)
ans =
                    CurrentMode: [1x1 matlab.uitools.internal.uimode]
                  DefaultUIMode: ''
                       Blocking: 0
                   FigureHandle: [1x1 Figure]
          WindowListenerHandles: [1x2 event.proplistener]
    WindowMotionListenerHandles: [1x2 event.proplistener]
                 DeleteListener: [1x1 event.listener]
            PreviousWindowState: []
                RegisteredModes: [1x1 matlab.uitools.internal.uimode]
>> struct(hManager.CurrentMode)
ans =
    WindowButtonMotionFcnInterrupt: 0
                UIControlInterrupt: 0
                   ShowContextMenu: 1
                         IsOneShot: 0
                    UseContextMenu: 'on'
                          Blocking: 0
               WindowJavaListeners: []
                    DeleteListener: [1x1 event.listener]
              FigureDeleteListener: [1x1 event.listener]
                    BusyActivating: 0
                              Name: 'Exploration.Zoom'
                      FigureHandle: [1x1 Figure]
             WindowListenerHandles: [1x2 event.proplistener]
                   RegisteredModes: []
                       CurrentMode: []
               ModeListenerHandles: []
               WindowButtonDownFcn: {@localWindowButtonDownFcn  [1x1 matlab.uitools.internal.uimode]}
                 WindowButtonUpFcn: []
             WindowButtonMotionFcn: {@localMotionFcn  [1x1 matlab.uitools.internal.uimode]}
                 WindowKeyPressFcn: []
               WindowKeyReleaseFcn: []
              WindowScrollWheelFcn: {@localButtonWheelFcn  [1x1 matlab.uitools.internal.uimode]}
                     KeyReleaseFcn: []
                       KeyPressFcn: {@localKeyPressFcn  [1x1 matlab.uitools.internal.uimode]}
                      ModeStartFcn: {@localStartZoom  [1x1 matlab.uitools.internal.uimode]}
                       ModeStopFcn: {@localStopZoom  [1x1 matlab.uitools.internal.uimode]}
                  ButtonDownFilter: []
                     UIContextMenu: []
                     ModeStateData: [1x1 struct]
                WindowFocusLostFcn: []
          UIControlSuspendListener: [1x1 event.listener]
      UIControlSuspendJavaListener: [1x1 handle.listener]
                   UserButtonUpFcn: []
               PreviousWindowState: []
                 ActionPreCallback: []
                ActionPostCallback: []
           WindowMotionFcnListener: [1x1 event.listener]
                       FigureState: [1x1 struct]
                        ParentMode: []
                     DefaultUIMode: ''
             CanvasContainerHandle: []
                            Enable: 'on'
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/enabling-user-callbacks-during-zoom-pan">Enabling user callbacks during zoom/pan</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/user-defined-tab-completions-take-2" rel="bookmark" title="User-defined tab completions &#8211; take 2">User-defined tab completions &#8211; take 2 </a> <small>Matlab has changed the mechanism that enables user-defined tab-completion of function inputs. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/determining-axes-zoom-state" rel="bookmark" title="Determining axes zoom state">Determining axes zoom state </a> <small>The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/enabling-user-callbacks-during-zoom-pan/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Hyperlink text labels</title>
		<link>https://undocumentedmatlab.com/articles/hyperlink-text-labels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hyperlink-text-labels</link>
					<comments>https://undocumentedmatlab.com/articles/hyperlink-text-labels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 21 Oct 2015 14:42:48 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6033</guid>

					<description><![CDATA[<p>Hyperlink labels can easily be added to Matlab GUIs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hyperlink-text-labels">Hyperlink text labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/transparent-labels" rel="bookmark" title="Transparent labels">Transparent labels </a> <small>Matlab labels can be set to a transparent background as well as padding. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>It is often useful to include hyperlinked text labels in GUIs. Such labels provide single-click access to important functionality, improve branding, and are non-intrusive action controls having a lower visual impact than a full-blown button. There are several ways that we can display such hyperlinks in Matlab GUIs, and today I will show one of my favorites.<br />
The basic idea is to create a Java text label control whose label displays an HTML link. The control is modified to change the mouse cursor when it hovers over the hyperlink, and a mouse-click callback is set to open the hyperlink target in the system browser:<br />
<figure style="width: 150px" class="wp-caption alignright"><img decoding="async" src="https://undocumentedmatlab.com/blog/wp-content/uploads/2009/04/button_link-150x150.png" alt="hyperlink text label" title="hyperlink text label" width="150" height="150" class="size-thumbnail wp-image-198" /><figcaption class="wp-caption-text">hyperlink text label</figcaption></figure></p>
<pre lang='matlab'>
% Create and display the text label
url = 'UndocumentedMatlab.com';
labelStr = ['<html>More info: <a href="">' url '</a></html>'];
jLabel = javaObjectEDT('javax.swing.JLabel', labelStr);
[hjLabel,hContainer] = javacomponent(jLabel, [10,10,250,20], gcf);
% Modify the mouse cursor when hovering on the label
hjLabel.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));
% Set the label's tooltip
hjLabel.setToolTipText(['Visit the ' url ' website']);
% Set the mouse-click callback
set(hjLabel, 'MouseClickedCallback', @(h,e)web(['http://' url], '-browser'))
</pre>
<p><span id="more-6033"></span><br />
Note the visual illusion here: we do not directly click the hyperlink (note that its <code>href</code> is empty), but rather the label control. The end-result is the same.<br />
Also note that this technique could be used to easily display clickable icons/images, including animated and transparent GIFs, by simply setting the label&#8217;s HTML string to display the relevant image. I have already shown how to do this in <a target="_blank" href="/articles/displaying-animated-gifs">another post</a>. Uses could range from clickable logo images to clickable help icons.<br />
We could also use a flat (borderless) button. I have already posted related articles about button customizations in Matlab GUIs (<a target="_blank" href="/articles/button-customization">here</a>, <a target="_blank" href="/articles/customizing-matlab-labels">here</a> and <a target="_blank" href="/articles/borderless-button-used-for-plot-properties">here</a>). In fact, I have already shown how we can use <a target="_blank" href="/articles/borderless-button-used-for-plot-properties">borderless buttons in Matlab axes</a> to display a non-obtrusive control for controlling plot properties. The code would be very similar to the above, except that we would use a <code>JButton</code> rather than a <code>JLabel</code>, and also need to <i>setBorder([])</i> and similar button-specific modifications. Buttons have a bit more functionality and customizability than simple text labels; the appearance would be the same, but the extra customizability may be handy in very special cases, although not for most use-cases.<br />
One of the benefits of using either <code>JLabels</code> or <code>JButtons</code> is that they enable <a target="_blank" href="/articles/uicontrol-callbacks">multiple callbacks</a> (e.g., <code>FocusGained,FocusLost</code>) and properties (e.g., <code>VerticalAlignment,ToolTipText</code>) that the standard Matlab text uicontrol does not provide (not to mention their builtin ability to display HTML, which Matlab&#8217;s uicontrol text labels do not posses).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hyperlink-text-labels">Hyperlink text labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/transparent-labels" rel="bookmark" title="Transparent labels">Transparent labels </a> <small>Matlab labels can be set to a transparent background as well as padding. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/hyperlink-text-labels/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Adding dynamic properties to graphic handles</title>
		<link>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-dynamic-properties-to-graphic-handles</link>
					<comments>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 16 Sep 2015 17:26:44 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6006</guid>

					<description><![CDATA[<p>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles">Adding dynamic properties to graphic handles</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" rel="bookmark" title="Adding custom properties to GUI objects">Adding custom properties to GUI objects </a> <small>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A client recently asked me to extend one of Matlab&#8217;s built-in graphic containers (<a target="_blank" href="/articles/matlab-layout-managers-uicontainer-and-relatives"><i><b>uiflowcontainer</b></i></a> in this specific case) with automatic scrollbars that would enable the container to act as a scroll-panel. The basic idea would be to dynamically monitor the container&#8217;s contents and when it is determined that they overflow the container&#8217;s boundaries, then attach horizontal/vertical scrollbars to enable scrolling the contents into view:<br />
<center><figure style="width: 350px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Scrollable Matlab container" src="https://undocumentedmatlab.com/images/uiflowcontainer_scroll.gif" title="Scrollable Matlab container" width="350" height="260" /><figcaption class="wp-caption-text">Scrollable Matlab container</figcaption></figure></center><br />
This may sound simple, but there are actually quite a few undocumented hacks that make this possible, including listening to <code>ObjectChildAdded/ObjectChildRemoved</code> events, location/size/visibility events, layout changes etc. Maybe I&#8217;ll blog about it in some future article.<br />
Today&#8217;s post is focused on a specific aspect of this project, attaching dynamic properties to the builtin <i><b>uiflowcontainer</b></i>, that would enable users to modify the container&#8217;s properties directly, as well as control aspects of the scrolling using the new properties: handles to the parent container, as well as the horizontal and vertical scrollbars, and even a new <i>refresh()</i> method.<br />
<span id="more-6006"></span><br />
The &#8220;textbook&#8221; approach to this would naturally be to create a new class that extends (inherits) <i><b>uiflowcontainer</b></i> and includes these new properties and methods. Unfortunately, for some reason that escapes my understanding, MathWorks saw fit to make all of its end-use graphic object classes <code>Sealed</code>, such that they cannot be extended by users. I did ask for this to be changed long ago, but the powers that be apparently decided that it&#8217;s better this way.<br />
So the fallback would be to create our own dedicated class having all the new properties as well as those of the original container, and ensure that all the property values are synchronized in both directions. This is probably achievable, if you have a spare few days and a masochistic state of mind. Being the lazy bum and authority-rebel that I am, I decided to take an alternate approach that would simply add my new properties to the built-in container handle. The secret lies in the undocumented function <i><b>schema.prop</b></i> (for HG1, R2014a and older) and the fully-documented <i><b>addprop</b></i> function (for HG2, R2014b and newer).<br />
In the examples below I use a panel, but this mechanism works equally well on any Matlab HG object: axes, lines, uicontrols, figures, etc.</p>
<h3 id="HG2">HG2 &#8211; addprop function</h3>
<p>The <i><b>addprop</b></i> function is actually a public method of the <code>dynamicprops</code> class. Both the <code>dynamicprops</code> class as well as its <i><b>addprop</b></i> function are <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/dynamicprops.addprop.html">fully documented</a>. What is NOT documented, as far as I could tell, is that all of Matlab&#8217;s builtin handle graphics objects indirectly inherit <code>dynamicprops</code>, via <code>matlab.graphics.Graphics</code>, which is a high-level superclass for all HG objects. The bottom line is that we can dynamically add run-time properties to any HG object, without affecting any other object. In other words, the new properties will only be added to the handles that we specifically request, and not to any others. This suits me just fine:</p>
<pre lang='matlab'>
hProp = addprop(hPanel, 'hHorizontalScrollBar');
hPanel.hHorizontalScrollBar = hMyScrollbar;
hProp.SetAccess = 'private';  % make this property read-only
</pre>
<p>The new property <code>hHorizontalScrollBar</code> is now added to the <code>hPanel</code> handle, and can be accessed just like any other read-only property. For example:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">get</span><span style="color: #080;">(</span>hPanel, <span style="color:#A020F0;">'hHorizontalScrollBar'</span><span style="color: #080;">)</span>
<span style="color: #0000FF;">ans</span> =
    JavaWrapper
&gt;&gt; hPanel.<span style="">hHorizontalScrollBar</span>
<span style="color: #0000FF;">ans</span> =
    JavaWrapper
&gt;&gt; hPanel.<span style="">hHorizontalScrollBar</span> = <span style="color: #33f;">123</span>
<span style="color: #FF0000;">You cannot set the read-only property 'hHorizontalScrollBar' of UIFlowContainer.</span></pre>
</div>
</div>
<p>Adding new methods is more tricky, since we do not have a corresponding <i>addmethod</i> function. The trick I used was to create a new property having the requested new method&#8217;s name, and set its read-only value to a handle of the requested function. For example:</p>
<pre lang='matlab'>
hProp = addprop(hPanel, 'refresh');
hPanel.refresh = @myRefreshFunc;
hProp.SetAccess = 'private';  % make this property read-only
</pre>
<p>We can then invoke the new <i>refresh</i> &#8220;method&#8221; using the familiar dot-notation:</p>
<pre lang='matlab'>hPanel.refresh();</pre>
<p>Note: if you ever need to modify the initial value in your code, you should revert the property&#8217;s <b>SetAccess</b> meta-property to <code>'public'</code> before Matlab will enable you to modify the value:</p>
<pre lang='matlab'>
try
    % This will raise an exception if the property already exists
    hProp = addprop(hPanel, propName);
catch
    % Property already exists - find it and set its access to public
    hProp = findprop(hPanel, propName);
    hProp.SetAccess = 'public';
end
hPanel.(propName) = newValue;
</pre>
<h3 id="HG1">HG1 &#8211; schema.prop function</h3>
<p>In HG1 (R2014a and earlier), we can use the undocumented <i><b>schema.prop</b></i> function to add a new property to any HG handle (which is a numeric value in HG1). Donn Shull <a target="_blank" href="/articles/udd-properties">wrote about <i><b>schema.prop</b></i></a> back in 2011, as part of his series of articles on UDD (Unified Data Dictionary, MCOS&#8217;s precursor). In fact, <i><b>schema.prop</b></i> is so useful that it has its own <a target="_blank" href="/articles/tag/schemaprop">blog tag here</a> and appears in no less than 15 separate articles (excluding today). With HG2&#8217;s debut 2 years ago, MathWorks tried very hard to rid the Matlab code corpus of all the legacy schema-based, replacing most major functionalities with MCOS-based HG2 code. But so far it has proven impossible to get rid of schema completely, and so schema code is still used extensively in Matlab to this day (R2015b). Search your Matlab path for &#8220;schema.prop&#8221; and see for yourself.<br />
Anyway, the basic syntax is this:</p>
<pre lang='matlab'>hProp = schema.prop(hPanel, propName, 'mxArray');</pre>
<p>The <code>'mxArray'</code> specifies that the new property can accept any data type. We can limit the property to only accept certain types of data by specifying a less-generic data type, among those recognized by UDD (<a target="_blank" href="/articles/udd-properties#DataType">details</a>).<br />
Note that the meta-properties of the returned <code>hProp</code> are somewhat different from those of HG2&#8217;s <code>hProp</code>. Taking this into account, here is a unified function that adds/updates a new property (with optional initial value) to any HG1/HG2 object:</p>
<pre lang='matlab'>
function addProp(hObject, propName, initialValue, isReadOnly)
    try
        hProp = addprop(hObject, propName);  % HG2
    catch
        try
            hProp = schema.prop(hObject, propName, 'mxArray');  % HG1
        catch
            hProp = findprop(hObject, propName);
        end
    end
    if nargin > 2
        try
            hProp.SetAccess = 'public';  % HG2
        catch
            hProp.AccessFlags.PublicSet = 'on';  % HG1
        end
        hObject.(propName) = initialValue;
    end
    if nargin > 3 && isReadOnly
        try
            % Set the property as read-only
            hProp.SetAccess = 'private';  % HG2
        catch
            hProp.AccessFlags.PublicSet = 'off';  % HG1
        end
    end
end
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles">Adding dynamic properties to graphic handles</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" rel="bookmark" title="Adding custom properties to GUI objects">Adding custom properties to GUI objects </a> <small>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>General-use object copy</title>
		<link>https://undocumentedmatlab.com/articles/general-use-object-copy?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=general-use-object-copy</link>
					<comments>https://undocumentedmatlab.com/articles/general-use-object-copy#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 06 May 2015 13:30:23 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[MCOS]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5782</guid>

					<description><![CDATA[<p>Matlab's dual internal serialization/deserialization functions can be used to create duplicates of any object. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/general-use-object-copy">General-use object copy</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/accessing-private-object-properties" rel="bookmark" title="Accessing private object properties">Accessing private object properties </a> <small>Private properties of Matlab class objects can be accessed (read and write) using some undocumented techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/class-object-tab-completion-and-improper-field-names" rel="bookmark" title="Class object tab completion &amp; improper field names">Class object tab completion &amp; improper field names </a> <small>Tab completions and property access can be customized for user-created Matlab classes. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>When using Matlab objects, either a Matlab class (MCOS) or any other (e.g., Java, COM, C# etc.), it is often useful to create a copy of the original object, complete with all internal property values. This enables modification of the new copy without affecting the original object. This is not important for MCOS value-class objects, since value objects use the COW (<i><a target="_blank" href="/articles/internal-matlab-memory-optimizations">Copy-on-Write</a>/Update</i>, a.k.a. <i>Lazy Copy</i>) and this is handled automatically by the Matlab interpreter when it detects that a change is made to the copy reference. However, it is very important for handle objects, where modifying any property of the copied object also modifies the original object.<br />
Most OOP languages include some sort of a <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Copy_constructor"><i>copy constructor</i></a>, which enables programmers to duplicate a handle/reference object, internal properties included, such that it becomes entirely separate from the original object. Unfortunately, Matlab did not include such a copy constructor until R2011a (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/matlab.mixin.copyable-class.html"><i><b>matlab.mixin.Copyable.copy()</b></i></a>).<br />
On Matlab R2010b and older, as well as on newer releases, we do not have a readily-available solution for handle object copy. Until now, that is.<br />
<span id="more-5782"></span><br />
There are several ways by which we can create such a copy function. We might call the main constructor to create a default object and then override its properties by iterating over the original object&#8217;s properties. This might work in some cases, but not if there is no default constructor for the object, or if there are side-effects to object property modifications. If we wanted to implement a deep (rather than shallow) copy, we&#8217;d need to recursively iterate over all the properties of the internal objects as well.<br />
A simpler solution might be to save the object to a temporary file (<i><b>tempname</b></i>, then load from that file (which creates a copy), and finally delete the temp file. This is nice and clean, but the extra I/O could be relatively slow compared to in-memory processing.<br />
Which leads us to today&#8217;s chosen solution, where we use Matlab&#8217;s builtin functions <i><b>getByteStreamFromArray</b></i> and <i><b>getArrayFromByteStream</b></i>, which I discussed last year as a way to easily <a target="_blank" href="/articles/serializing-deserializing-matlab-data">serialize and deserialize Matlab data</a> of any type. Specifically, <i><b>getArrayFromByteStream</b></i> has the side-effect of creating a duplicate of the serialized data, which is perfect for our needs here (note that these pair of function are only available on R2010b or newer; on R2010a or older we can still serialize via a temp file):</p>
<pre lang='matlab'>
% Copy function - replacement for matlab.mixin.Copyable.copy() to create object copies
function newObj = copy(obj)
    try
        % R2010b or newer - directly in memory (faster)
        objByteArray = getByteStreamFromArray(obj);
        newObj = getArrayFromByteStream(objByteArray);
    catch
        % R2010a or earlier - serialize via temp file (slower)
        fname = [tempname '.mat'];
        save(fname, 'obj');
        newObj = load(fname);
        newObj = newObj.obj;
        delete(fname);
    end
end
</pre>
<p>This function can be placed anywhere on the Matlab path and will work on all recent Matlab releases (including R2010b and older), any type of Matlab data (including value or handle objects, UDD objects, structs, arrays etc.), as well as external objects (Java, C#, COM). In short, it works on anything that can be assigned to a Matlab variable:</p>
<pre lang='matlab'>
obj1 = ... % anything really!
obj2 = obj1.copy();  % alternative #1
obj2 = copy(obj1);   % alternative #2
</pre>
<p>Alternative #1 may look &#8220;nicer&#8221; to a computer scientist, but alternative #2 is preferable because it also handles the case of non-object data (e.g., [] or &#8216;abc&#8217; or <i><b>magic(5)</b></i> or a struct or cell array), whereas alternative #1 would error in such cases.<br />
In any case, using either alternatives, we no longer need to worry about inheriting our MCOS class from <i><b>matlab.mixin.Copyable</b></i>, or backward compatibility with R2010b and older (I may possibly be bashed for this statement, but in my eyes future compatibility is less important than backward compatibility). This is not such a wild edge-case. In fact, I came across the idea for this post last week, when I developed an MCOS project for a consulting client that uses both R2010a and R2012a, and the same code needed to run on both Matlab releases.<br />
Using the serialization functions also solves the case of creating copies for Java/C#/COM objects, which currently have no other solution, except if these objects happen to contain their own copy method.<br />
In summary, using Matlab&#8217;s undocumented builtin serialization functions enables easy implementation of a very efficient (in-memory) copy constructor, which is expected to work across all Matlab types and many releases, without requiring any changes to existing code &#8211; just placing the above <i><b>copy</b></i> function on the Matlab path. This is expected to continue working properly until Matlab decides to remove the serialization functions (which should hopefully never happen, as they are <i>so</i> useful).<br />
Sometimes, the best solutions lie not in sophisticated new features (e.g., <i><b>matlab.mixin.Copyable</b></i>), but by using plain ol&#8217; existing building blocks. There&#8217;s a good lesson to be learned here I think.<br />
p.s. &#8211; I do realize that <i><b>matlab.mixin.Copyable</b></i> provides the nice feature of enabling users to control the copy process, including implementing deep or shallow or selective copy. If that&#8217;s your need and you have R2011a or newer then good for you, go ahead and inherit Copyable. Today&#8217;s post was meant for the regular Joe who doesn&#8217;t need this fancy feature, but does need to support R2010b, and/or a simple way to clone Java/C#/COM objects.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/general-use-object-copy">General-use object copy</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/accessing-private-object-properties" rel="bookmark" title="Accessing private object properties">Accessing private object properties </a> <small>Private properties of Matlab class objects can be accessed (read and write) using some undocumented techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/class-object-tab-completion-and-improper-field-names" rel="bookmark" title="Class object tab completion &amp; improper field names">Class object tab completion &amp; improper field names </a> <small>Tab completions and property access can be customized for user-created Matlab classes. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/general-use-object-copy/feed</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
	</channel>
</rss>
