<?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/category/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>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>Additional license data</title>
		<link>https://undocumentedmatlab.com/articles/additional-license-data?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=additional-license-data</link>
					<comments>https://undocumentedmatlab.com/articles/additional-license-data#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 15 Feb 2017 18:01:55 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6852</guid>

					<description><![CDATA[<p>Additional meta-data about installed toolboxes can be retrieved in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/additional-license-data">Additional license data</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/customizing-axes-part-4-additional-properties" rel="bookmark" title="Customizing axes part 4 &#8211; additional properties">Customizing axes part 4 &#8211; additional properties </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</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/sparse-data-math-info" rel="bookmark" title="Sparse data math info">Sparse data math info </a> <small>Matlab contains multiple libraries for handling sparse data. These can report very detailed internal info. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/simulink-data-dictionary" rel="bookmark" title="Simulink Data Dictionary">Simulink Data Dictionary </a> <small>Simulink contains undocumented public API for access to its data dictionary functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab&#8217;s <i><b>license</b></i> function returns the primary license number/ID used by Matlab, but no information about the various toolboxes that may be installed. The <i><b>ver</b></i> function returns a bit more information, listing the version number and installation date of installed toolboxes (even user toolboxes, such as my <a href="/IB-Matlab" target="_blank">IB-Matlab</a> toolbox). However, no additional useful information is provided beyond that:</p>
<pre lang="matlab">
>> license
ans =
123456   % actual number redacted
>> ver
----------------------------------------------------------------------------------------------------
MATLAB Version: 9.1.0.441655 (R2016b)
MATLAB License Number: 123456
Operating System: Microsoft Windows 7 Professional  Version 6.1 (Build 7601: Service Pack 1)
Java Version: Java 1.7.0_60-b19 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
----------------------------------------------------------------------------------------------------
MATLAB                                                Version 9.1         (R2016b)
Curve Fitting Toolbox                                 Version 3.5.4       (R2016b)
Database Toolbox                                      Version 7.0         (R2016b)
Datafeed Toolbox                                      Version 5.4         (R2016b)
Financial Instruments Toolbox                         Version 2.4         (R2016b)
Financial Toolbox                                     Version 5.8         (R2016b)
GUI Layout Toolbox                                    Version 2.2.1       (R2015b)
Global Optimization Toolbox                           Version 3.4.1       (R2016b)
IB-Matlab - Matlab connector to InteractiveBrokers    Version 1.89        Expires: 1-Apr-2018
Image Processing Toolbox                              Version 9.5         (R2016b)
MATLAB Coder                                          Version 3.2         (R2016b)
MATLAB Report Generator                               Version 5.1         (R2016b)
Optimization Toolbox                                  Version 7.5         (R2016b)
Parallel Computing Toolbox                            Version 6.9         (R2016b)
Statistical Graphics Toolbox                          Version 1.2
Statistics and Machine Learning Toolbox               Version 11.0        (R2016b)
>> v = ver
v =
  1×16 struct array with fields:
    Name
    Version
    Release
    Date
>> v(1)
ans =
  struct with fields:
       Name: 'Curve Fitting Toolbox'
    Version: '3.5.4'
    Release: '(R2016b)'
       Date: '25-Aug-2016'
>> v(8)
ans =
  struct with fields:
       Name: 'IB-Matlab - Matlab connector to InteractiveBrokers'
    Version: '1.89'
    Release: 'Expires: 1-Apr-2018'
       Date: '02-Feb-2017'
</pre>
<p>It is <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/347230" rel="nofollow" target="_blank">sometimes useful</a> to know which license number &#8220;owns&#8221; which product/toolbox, and the expiration date is associated with each of them. Unfortunately, there is no documented way to retrieve this information in Matlab &#8211; the only documented way is to go to your account section on the MathWorks website and check there.<br />
Luckily, there is a simpler way that can be used to retrieve additional information, from right inside Matlab, using <i><b>matlab.internal.licensing.getFeatureInfo</b></i>:<br />
<span id="more-6852"></span></p>
<pre lang="matlab">
>> all_data = matlab.internal.licensing.getFeatureInfo
all_data =
  23×1 struct array with fields:
    feature
    expdate
    keys
    license_number
    entitlement_id
>> all_data(20)
ans =
  struct with fields:
           feature: 'optimization_toolbox'
           expdate: '31-mar-2018'
              keys: 0
    license_number: '123456'
    entitlement_id: '1409891'
>> all_data(21)
ans =
  struct with fields:
           feature: 'optimization_toolbox'
           expdate: '07-mar-2017'
              keys: 0
    license_number: 'DEMO'
    entitlement_id: '3749959'
</pre>
<p>As can be seen in this example, I have the Optimization toolbox licensed under my main Matlab license (123456 [actual number redacted]) until 31-mar-2018, and also licensed under a trial (DEMO) license that expires in 3 weeks. As long as a toolbox has any future expiration date, it will continue to function, so in this case I&#8217;m covered until March 2018.<br />
We can also request information about a specific toolbox (&#8220;feature&#8221;):</p>
<pre lang="matlab">
>> data = matlab.internal.licensing.getFeatureInfo('matlab')
data =
  3×1 struct array with fields:
    feature
    expdate
    keys
    license_number
    entitlement_id
>> data(1)
data =
  struct with fields:
           feature: 'matlab'
           expdate: '31-mar-2018'
              keys: 0
    license_number: '123456'
    entitlement_id: '1409891'
</pre>
<p>The drawback of this functionality is that it only provides information about MathWorks&#8217; toolbox, not any user-provided toolboxes (such as my IB-Matlab connector, or MathWorks&#8217; own GUI Layout toolbox). Also, some of the toolbox names may be difficult to understand (&#8220;gads_toolbox&#8221; apparently stands for the Global Optimization Toolbox, for example):</p>
<pre lang="matlab">
>> {all_data.feature}
ans =
  1×23 cell array
  Columns 1 through 4
    'curve_fitting_toolbox'    'database_toolbox'    'datafeed_toolbox'    'distrib_computing_toolbox'
  Columns 5 through 8
    'distrib_computing_toolbox'    'excel_link'    'fin_instruments_toolbox'    'financial_toolbox'
  Columns 9 through 15
    'gads_toolbox'    'gads_toolbox'    'image_toolbox'    'image_toolbox'    'matlab'    'matlab'    'matlab'
  Columns 16 through 20
    'matlab_coder'    'matlab_coder'    'matlab_report_gen'    'matlab_report_gen'    'optimization_toolbox'
  Columns 21 through 23
    'optimization_toolbox'    'optimization_toolbox'    'statistics_toolbox'
</pre>
<p>A related undocumented builtin function is <i><b>matlab.internal.licensing.getLicInfo</b></i>:</p>
<pre lang="matlab">
% Information on a single toolbox/product:
>> matlab.internal.licensing.getLicInfo('matlab')
ans =
  struct with fields:
     license_number: {'123456'  'Prerelease'  'T3749959'}
    expiration_date: {'31-mar-2018'  '30-sep-2016'  '07-mar-2017'}
% Information on multiple toolboxes/products:
>> matlab.internal.licensing.getLicInfo({'matlab', 'image_toolbox'})  % cell array of toolbox/feature names
ans =
  1×2 struct array with fields:
    license_number
    expiration_date
% The full case-insensitive names of the toolboxes can also be used:
>> matlab.internal.licensing.getLicInfo({'Matlab', 'Image Processing toolbox'})
ans =
  1×2 struct array with fields:
    license_number
    expiration_date
% And here's how to get the full list (MathWorks products only):
>> v=ver; data=matlab.internal.licensing.getLicInfo({v.Name})
data =
  1×16 struct array with fields:
    license_number
    expiration_date
</pre>
<p>I have [still] not found any way to associate a user toolbox/product (such as my IB-Matlab) in a way that will report it in a unified manner with the MathWorks products. If anyone finds a way to do this, please do let me know.<br />
p.s. &#8211; don&#8217;t even think of asking questions or posting comments on this website related to illegal uses or hacks of the Matlab license&#8230;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/additional-license-data">Additional license data</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/customizing-axes-part-4-additional-properties" rel="bookmark" title="Customizing axes part 4 &#8211; additional properties">Customizing axes part 4 &#8211; additional properties </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</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/sparse-data-math-info" rel="bookmark" title="Sparse data math info">Sparse data math info </a> <small>Matlab contains multiple libraries for handling sparse data. These can report very detailed internal info. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/simulink-data-dictionary" rel="bookmark" title="Simulink Data Dictionary">Simulink Data Dictionary </a> <small>Simulink contains undocumented public API for access to its data dictionary functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/additional-license-data/feed</wfw:commentRss>
			<slash:comments>6</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 fetchpriority="high" 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>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>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 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>
		<item>
		<title>savezip utility</title>
		<link>https://undocumentedmatlab.com/articles/savezip-utility?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=savezip-utility</link>
					<comments>https://undocumentedmatlab.com/articles/savezip-utility#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 04 Sep 2014 18:14:12 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Book]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4982</guid>

					<description><![CDATA[<p>Matlab data can be serialized and saved into a ZIP/GZIP file, and loaded back. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/savezip-utility">savezip utility</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/screencapture-utility" rel="bookmark" title="ScreenCapture utility">ScreenCapture utility </a> <small>The ScreenCapture utility uses purely-documented Matlab for capturing a screen region as an image from within Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/interesting-uitree-utility" rel="bookmark" title="An interesting uitree utility">An interesting uitree utility </a> <small>ExploreStruct is a utility that shows how custom uitrees can be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few months ago I wrote about <a target="_blank" href="/articles/serializing-deserializing-matlab-data">Matlab&#8217;s undocumented serialization/deserialization functions</a>, <i><b>getByteStreamFromArray</b></i> and <i><b>getArrayFromByteStream</b></i>. This could be very useful for both sending Matlab data across a network (thus avoiding the need to use a shared file), as well as for much faster data-save using the -V6 MAT format (<i><b>save -v6 &#8230;</b></i>).<br />
<span class="alignright"><img decoding="async" src="https://undocumentedmatlab.com/images/serial2_zip.jpg" width="114" height="148"/></span> As a followup to that article, in some cases it might be useful to use ZIP/GZIP compression, rather than Matlab&#8217;s proprietary MAT format or an uncompressed byte-stream.<br />
Unfortunately, Matlab&#8217;s compression functions <i><b>zip</b></i>, <i><b>gzip</b></i> and <i><b>tar</b></i> do not really help run-time performance, but rather hurt it. The reason is that we would be paying the I/O costs three times: first to write the original (uncompressed) file, then to have <i><b>zip</b></i> or its counterparts read it, and finally to save the compressed file. <i><b>tar</b></i> is worst in this respect, since it does both a GZIP compression and a simple tar concatenation to get a standard <i>tar.gz</i> file. Using <i><b>zip/gzip/tar</b></i> only makes sense if we need to pass the data file to some external program on some remote server, whereby compressing the file could save transfer time. But as far as our Matlab program&#8217;s performance is concerned, these functions bring little value.<br />
In contrast to file-system compression, which is what <i><b>zip/gzip/tar</b></i> do, on-the-fly (memory) compression makes more sense and can indeed help performance. In this case, we are compressing the data in memory, and directly saving to file the resulting (compressed) binary data. The following example compresses <i><b>int8</b></i> data, such as the output of our <i><b>getByteStreamFromArray</b></i> serialization:<br />
<span id="more-4982"></span></p>
<pre lang='matlab'>
% Serialize the data into a 1D array of uint8 bytes
dataInBytes = getByteStreamFromArray(data);
% Parse the requested output filename (full path name)
[fpath,fname,fext] = fileparts(filepath);
% Compress in memory and save to the requested file in ZIP format
fos = java.io.FileOutputStream(filepath);
%fos = java.io.BufferedOutputStream(fos, 8*1024);  % not really important (*ZipOutputStream are already buffered), but doesn't hurt
if strcmpi(fext,'.gz')
    % Gzip variant:
    zos = java.util.zip.GZIPOutputStream(fos);  % note the capitalization
else
    % Zip variant:
    zos = java.util.zip.ZipOutputStream(fos);  % or: org.apache.tools.zip.ZipOutputStream as used by Matlab's zip.m
    ze  = java.util.zip.ZipEntry('data.dat');  % or: org.apache.tools.zip.ZipEntry as used by Matlab's zip.m
    ze.setSize(originalDataSizeInBytes);
    zos.setLevel(9);  % set the compression level (0=none, 9=max)
    zos.putNextEntry(ze);
end
zos.write(dataInBytes, 0, numel(dataInBytes));
zos.finish;
zos.close;
</pre>
<p>This will directly create a zip archive file in the current folder. The archive will contain a single entry (<i>data.dat</i>) that contains our original data. Note that <i>data.dat</i> is entirely virtual: it was never actually created, saving us its associated I/O costs. In fact we could have called it simply <i>data</i>, or whatever other valid file name.<br />
Saving to a gzip file is even simpler, since GZIP files have single file entries. There is no use for a <code>ZipEntry</code> as in zip archives that may contain multiple file entries.<br />
Note that while the resulting ZIP/GZIP file is often smaller in size than the corresponding MAT file generated by Matlab&#8217;s <i><b>save</b></i>, it is not necessarily faster. In fact, except on slow disks or network drives, <i><b>save</b></i> may well outperform this mechanism. However, in some cases, the reduced file size may save enough I/O to offset the extra processing time. Moreover, GZIP is typically much faster than either ZIP or Matlab&#8217;s <i><b>save</b></i>.</p>
<h3 id="load">Loading data from ZIP/GZIP</h3>
<p>Similar logic applies to reading compressed data: We could indeed use <i><b>unzip/gunzip/untar</b></i>, but these would increase the I/O costs by reading the compressed file, saving the uncompressed version, and then reading that uncompressed file into Matlab.<br />
A better solution would be to read the compressed file directly into Matlab. Unfortunately, the corresponding input-stream classes do not have a <i>read()</i> method that returns a byte array. We therefore use a small hack to copy the input stream into a <code>ByteArrayOutputStream</code>, using Matlab&#8217;s own stream-copier class that is used within all of Matlab&#8217;s compression and decompression functions:</p>
<pre lang='matlab'>
% Parse the requested output filename (full path name)
[fpath,fname,fext] = fileparts(filepath);
% Get the serialized data
streamCopier = com.mathworks.mlwidgets.io.InterruptibleStreamCopier.getInterruptibleStreamCopier;
baos = java.io.ByteArrayOutputStream;
fis  = java.io.FileInputStream(filepath);
if strcmpi(fext,'.gz')
    % Gzip variant:
    zis  = java.util.zip.GZIPInputStream(fis);
else
    % Zip variant:
    zis  = java.util.zip.ZipInputStream(fis);
    % Note: although the ze & fileName variables are unused in the Matlab
    % ^^^^  code below, they are essential in order to read the ZIP!
    ze = zis.getNextEntry;
    fileName = char(ze.getName);  %#ok<nasgu> => 'data.dat' (virtual data file)
end
streamCopier.copyStream(zis,baos);
fis.close;
data = baos.toByteArray;  % array of Matlab int8
% Deserialize the data back into the original Matlab data format
% Note: the zipped data is int8 => need to convert into uint8:
% Note2: see discussion with Martin in the comments section below
if numel(data) < 1e5
    data = uint8(mod(int16(data),256))';
else
    data = typecast(data, 'uint8');
end
data = getArrayFromByteStream(data);
</pre>
<p>Note that when we deserialize, we have to convert the unzipped <i><b>int8</b></i> byte-stream into a <i><b>uint8</b></i> byte-stream that <i><b>getArrayFromByteStream</b></i> can process (we don't need to do this during serialization).</p>
<h3 id="FEX">The SAVEZIP utility</h3>
<p>I have uploaded a utility called <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/47698-savezip">SAVEZIP</a> to the Matlab File Exchange which includes the <i><b>savezip</b></i> and <i><b>loadzip</b></i> functions. These include the code above, plus some extra sanity checks and data processing. Usage is quite simple:</p>
<pre lang='matlab'>
savezip('myData', magic(4))   %save data to myData.zip in current folder
savezip('myData', 'myVar')    %save myVar to myData.zip in current folder
savezip('myData.gz', 'myVar') %save data to myData.gz in current folder
savezip('data\myData', magic(4))    %save data to .\data\myData.zip
savezip('data\myData.gz', magic(4)) %save data to .\data\myData.gz
myData = loadzip('myData');
myData = loadzip('myData.zip');
myData = loadzip('data\myData');
myData = loadzip('data\myData.gz');
</pre>
<p>Jan Berling has written another variant of the idea of using <i><b>getByteStreamFromArray</b></i> and <i><b>getArrayFromByteStream</b></i> for saving/loading data from disk, in this case in an uncompressed manner. He put it all in his <i><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/45743-bytestream-save-toolbox">Bytestream Save Toolbox</a></i> on the File Exchange.</p>
<h3 id="transmit">Transmitting compressed data via the network</h3>
<p>If instead of saving to a file we wish to transmit the compressed data to a remote process (or to save it ourselves later), we can simply wrap our <code>ZipOutputStream</code> with a <code>ByteArrayOutputStream</code>  rather than a <code>FileOutputStream</code>. For example, on the way out:</p>
<pre lang='matlab'>
baos = java.io.ByteArrayOutputStream;
if isGzipVarant
    zos = java.util.zip.GZIPOutputStream(baos);
else  % Zip variant
    zos = java.util.zip.ZipOutputStream(baos);
    ze  = java.util.zip.ZipEntry('data.dat');
    ze.setSize(numel(data));
    zos.setLevel(9);
    zos.putNextEntry(ze);
end
dataInBytes = int8(data);  % or: getByteStreamFromArray(data)
zos.write(dataInBytes,0,numel(dataInBytes));
zos.finish;
zos.close;
compressedDataArray = baos.toByteArray;  % array of Matlab int8
</pre>
<p>I leave it as an exercise to the reader to make the corresponding changes for the receiving end.</p>
<h3 id="Succinctly">New introductory Matlab book</h3>
<p>Matlab has a plethora of introductory books. But I have a special affection to one that was released only a few days ago: <i><a target="_blank" rel="nofollow" href="http://www.syncfusion.com/resources/techportal/ebooks/matlab">MATLAB Succinctly</a></i> by Dmitri Nesteruk, for which I was a technical editor/reviewer. It's a very readable and easy-to-follow book, and it's totally free, so go ahead and download.<br />
<span class="alignright"><a target="_blank" rel="nofollow" href="http://www.syncfusion.com/resources/techportal/ebooks/matlab"><img loading="lazy" decoding="async" alt="MATLAB Succinctly book by Dmitri Nesteruk" src="https://d2g29cya9iq7ip.cloudfront.net/content/images/downloads/ebooks/Matlab.png?v=01092014061434" title="MATLAB Succinctly book by Dmitri Nesteruk" width="225" height="300" /></a></span> This title adds to the large (and growing) set of free ~100-page introductory titles by <a target="_blank" rel="nofollow" href="http://www.syncfusion.com">Syncfusion</a>, on a wide variety of programming languages and technologies. Go ahead and <a target="_blank" rel="nofollow" href="http://www.syncfusion.com/resources/techportal/ebooks">download these books</a> as well. While you're at it, take a look at Syncfusion's set of professional components and spread the word. If Syncfusion gets enough income from such incoming traffic, they may continue to support their commendable project of similar free IT-related titles.<br />
This may be a good place to update that my own [second] book, <i><a target="_blank" href="/books/matlab-performance">Accelerating MATLAB Performance</a></i>, is nearing completing, and is currently in advanced copy-editing stage. It turned out that there was a lot more to Matlab performance than I initially realized. The book size (and writing time) doubled, and it turned out to be a hefty ~750 pages packed full with performance improvement tips. I'm still considering the cover image (ideas anyone?) and working on the index, but the end is now in sight. The book should be in your favorite bookstore this December. If you can't wait until then, and/or if you'd rather use the real McCoy, consider <a target="_blank" href="/consulting">inviting me</a> for a consulting session...<br />
<u><b>Addendum December 16, 2014</b></u>: I am pleased to announce that my book, <i><b>Accelerating MATLAB Performance</b></i>, is now published (<a target="_blank" href="/books/matlab-performance">additional information</a>).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/savezip-utility">savezip utility</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/screencapture-utility" rel="bookmark" title="ScreenCapture utility">ScreenCapture utility </a> <small>The ScreenCapture utility uses purely-documented Matlab for capturing a screen region as an image from within Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/interesting-uitree-utility" rel="bookmark" title="An interesting uitree utility">An interesting uitree utility </a> <small>ExploreStruct is a utility that shows how custom uitrees can be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/savezip-utility/feed</wfw:commentRss>
			<slash:comments>22</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented feature list</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-feature-list?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-feature-list</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-feature-list#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 19 Mar 2014 18:00:30 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4724</guid>

					<description><![CDATA[<p>A list of undocumented MATLAB features can be retrieved. Here's how... </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-feature-list">Undocumented feature list</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/the-hotlinks-feature" rel="bookmark" title="The HotLinks feature">The HotLinks feature </a> <small>feature('HotLinks') can be used to temporarily disable hyperlinks and other markups in the Matlab console. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Three years ago I posted an article on <a target="_blank" href="/articles/undocumented-feature-function/">Matlab&#8217;s undocumented <i><b>feature</b></i> function</a>. <i><b>feature</b></i> is a Matlab function that enables access to undocumented internal Matlab functionality. Most of this functionality is not very useful, but in some cases it could indeed be very interesting. As sometimes happens, this innocent-enough article generated a lot of interest, both online and offline. Perhaps the reason was that in this article I listed the known list of supported features with a short explanation and references were available. At the time, this was the only comprehensive such listing, which I manually collected from numerous sources. For this reason I was delighted to receive Yves Piguet&#8217;s <a target="_blank" href="/articles/undocumented-feature-function/#comment-34109">tip</a> about the availability of a programmatic interface for a full listing of features:</p>
<pre lang='matlab'>
>> list = feature('list')   % 260 features in R2013b
list =
1x260 struct array with fields:
    name
    value
    has_callback
    has_builtin
    call_count
</pre>
<p>Which can be listed as follows:</p>
<pre lang='matlab'>
for i = 1 : length(list)
   fprintf('%35s has_cb=%d has_bi=%d calls=%d val=%g\n', ...
      list(i).name, list(i).has_callback, list(i).has_builtin, list(i).call_count, list(i).value);
end
                    100 has_cb=0 has_bi=1 calls=0 val=1
                    102 has_cb=0 has_bi=1 calls=0 val=1
                     12 has_cb=0 has_bi=1 calls=0 val=1
                     14 has_cb=0 has_bi=1 calls=0 val=1
                     25 has_cb=0 has_bi=1 calls=0 val=1
                    300 has_cb=0 has_bi=0 calls=0 val=1
                    301 has_cb=0 has_bi=0 calls=0 val=1
                     44 has_cb=0 has_bi=1 calls=0 val=1
                     45 has_cb=0 has_bi=1 calls=0 val=1
                      7 has_cb=0 has_bi=0 calls=0 val=1
                      8 has_cb=0 has_bi=1 calls=0 val=1
                      9 has_cb=0 has_bi=0 calls=0 val=1
                  accel has_cb=0 has_bi=1 calls=0 val=0
         AccelBlockSize has_cb=0 has_bi=1 calls=0 val=0
          AccelMaxTemps has_cb=0 has_bi=1 calls=0 val=0
    AccelThreadBlockMin has_cb=0 has_bi=1 calls=0 val=0
              allCycles has_cb=0 has_bi=1 calls=0 val=0
 AllWarningsCanBeErrors has_cb=1 has_bi=0 calls=0 val=0
           ArrayEditing has_cb=0 has_bi=0 calls=0 val=1
       AutomationServer has_cb=0 has_bi=1 calls=0 val=0
              CachePath has_cb=0 has_bi=0 calls=0 val=1
     CaptureScreenCount has_cb=0 has_bi=0 calls=0 val=0
       CheckMallocClear has_cb=0 has_bi=0 calls=0 val=1
                    ... (etc. etc.)
</pre>
<p>Unfortunately, in the latest Matlab R2014a, which was released last week, this nice feature has been removed:</p>
<pre lang='matlab'>
>> list = feature('list')
Error using feature
Feature list not found
</pre>
<p>Luckily, the list can still be retrieved programmatically, using an undocumented MEX library function. Place the following in a file called <i>feature_list.cpp</i>:<br />
<span id="more-4724"></span></p>
<pre lang='c'>
#include "mex.h"
void svListFeatures(int, mxArray_tag** const, int, mxArray_tag** const);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    svListFeatures(1,plhs,0,NULL);
}
</pre>
<p>Now compile this MEX file:</p>
<pre lang='matlab'>
if isunix
   mex('feature_list.cpp',['-L',matlabroot,'/bin/',computer('arch')],'-lmwservices');
else
   mex('feature_list.cpp','-llibmwservices');
end
</pre>
<p>As you can see, all this MEX function does is just call the <i>svListFeatures()</i> function from the <i>libmwservices</i> dynamic/shared library.<br />
We can now run this MEX function directly in Matlab:</p>
<pre lang='matlab'>
>> list = feature_list
list =
1x273 struct array with fields:
    name
    value
    has_callback
    has_builtin
    call_count
</pre>
<p>Running both the new <i><b>feature_list</b></i> and the previous <i><b>feature</b>(&#8216;list&#8217;)</i> on previous Matlab releases produces exactly the same result, showing that under the hood, <i><b>feature</b>(&#8216;list&#8217;)</i> was basically just calling <i>libmwservices</i>&#8216;s <i>svListFeatures()</i> function.<br />
There are 273 undocumented features in R2014a: 20 were added and 7 were removed compared to R2013b. For those interested, the modified features in the past two releases are:</p>
<ul>
<li>R2013b:
<ol>
<li>ConvertAllDoublesToHandles (added)</li>
<li>DrawnowNowaitFeature (added)</li>
<li>getsimd (added)</li>
<li>CoreDump (removed)</li>
</ol>
</li>
<li>R2014a:
<ol>
<li>GPUAllowPartialSharedDataCopies (added)</li>
<li>GPUAllowSharedDataCopies (added)</li>
<li>GetOpenGLData (added)</li>
<li>GetOpenGLInfo (added)</li>
<li>HGUpdateErrorChecking (added)</li>
<li>JVMShutdown (added)</li>
<li>LoadHG1FigFileWithHG1Defaults (added)</li>
<li>OpenGLBitmapZbufferBug (added)</li>
<li>OpenGLClippedImageBug (added)</li>
<li>OpenGLDockingBug (added)</li>
<li>OpenGLEraseModeBug (added)</li>
<li>OpenGLLineSmoothingBug (added)</li>
<li>OpenGLPolygonOffsetBiasBug (added)</li>
<li>OpenGLVerbose (added)</li>
<li>OpenGLWobbleTesselatorBug (added)</li>
<li>SaveFigFileWithHG1Defaults (added)</li>
<li>ShutdownReportLevel (added)</li>
<li>UseGenericOpenGL (added)</li>
<li>crash_mode (added)</li>
<li>isLightweightEval (added)</li>
<li>EnableBangErrors (removed)</li>
<li>EnableJavaAsGObject (removed)</li>
<li>List (removed) &#8211; this is actually the reason for today&#8217;s article!</li>
<li>hwtic (removed)</li>
<li>hwtoc (removed)</li>
<li>oldtictoc (removed)</li>
<li>timing (removed)</li>
</ol>
</li>
</ul>
<p>Happy digging!</p>
<div id="Packt">p.s. &#8211; Packt publishing, which publishes IT books, has a great deal on ebooks until March 26 &#8211; <a target="_blank" rel="nofollow" href="http://bit.ly/1j26nPN">buy 1 get 1 free</a>. Some of their books are Matlab-related. Check it out!</div>
<p><span id="R2015a"></span><br />
<b><u>Addendum July 18, 2016</u></b>: Since R2015a, <i><b>feature</b>(&#8216;list&#8217;)</i> returns an empty array. A reader of this blog, Mikhail P, reported the following workaround, by temporarily setting the <code>MWE_INSTALL</code> environment variable (that should then be reset, since it is used in other locations too):</p>
<pre lang="matlab">
% The following was run in R2016b
>> setenv('MWE_INSTALL','1'); list = feature('list'), setenv('MWE_INSTALL');
list =
  1×266 struct array with fields:
    name
    value
    has_callback
    has_builtin
    call_count
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-feature-list">Undocumented feature list</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/the-hotlinks-feature" rel="bookmark" title="The HotLinks feature">The HotLinks feature </a> <small>feature('HotLinks') can be used to temporarily disable hyperlinks and other markups in the Matlab console. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-feature-list/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
