<?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>Semi-documented function &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/category/semi-documented-function/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 05 Feb 2020 08:57:49 +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>Sliders in Matlab GUI &#8211; part 2</title>
		<link>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sliders-in-matlab-gui-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 05 Jul 2018 11:40:56 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7728</guid>

					<description><![CDATA[<p>Matlab contains a variety of ways to define/display slider controls in GUI windows. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2">Sliders in Matlab GUI &#8211; part 2</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/sliders-in-matlab-gui" rel="bookmark" title="Sliders in Matlab GUI">Sliders in Matlab GUI </a> <small>Professional-looking slider controls can easily be integrated in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Exactly 3 years ago I posted about various <a href="/articles/sliders-in-matlab-gui" target="_blank">alternatives for embedding sliders in Matlab GUI</a>. Today I will follow up on that post with a description of yet another undocumented builtin alternative &#8211; <i><b>controllib.widget.Slider</b></i>. A summary of the various alternatives can be seen in the following screenshot:<br />
<center><figure style="width: 344px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/sliders.gif" alt="Slider alternatives in Matlab GUI" title="Slider alternatives in Matlab GUI" width="344" height="303" /><figcaption class="wp-caption-text">Slider alternatives in Matlab GUI</figcaption></figure></center><br />
The <i><b>controllib.widget.Slider</b></i> component is a class in Matlab&#8217;s internal <code>controllib</code> package (last week I discussed a different utility function in this package, <a href="/articles/string-char-compatibility" target="_blank"><i><b>controllib.internal.util.hString2Char</b></i></a>).<br />
<span id="more-7728"></span><br />
<i><b>controllib.widget.Slider</b></i> accepts 3 input arguments: containing figure handle, position in pixels, and data values. For example:</p>
<pre lang="matlab">
>> hSlider = controllib.widget.Slider(gcf, [10,10,100,50], 5:25)
hSlider =
  Slider with properties:
        Data: [6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25]
       Index: 11
       Value: 15
    FontSize: 8
    Position: [10 10 100 50]
</pre>
<p>This creates an invisible axes at the specified figure location and displays graphic axes objects that provide the appearance of the slider. When you move the slider&#8217;s knob, or click its centerline or arrows (&#8220;Steppers&#8221;), the slider&#8217;s value changes accordingly.<br />
You can attach a callback function to the slider as follows:</p>
<pre lang="matlab">
myCallback = @(h,e) disp(h.Value);  % as an example
addlistener(hSlider, 'ValueChanged', myCallback);
</pre>
<p>Note that <i><b>controllib.widget.Slider</b></i> is based on pure-Matlab code and fully-supported functionality. The Matlab source code is available (<i>%matlabroot%/toolbox/shared/controllib/graphics/+controllib/+widget/Slider.m</i>) and quite readable. So while it does not actually work with the new web-based uifigures, is should be relatively easy to adapt the code so that this component could be displayed in such uifigures.<br />
Below is a script to recreate the screenshot above. Note the two alternative mechanisms for setting properties (Java setter-method notation, and HG set notation):</p>
<pre lang="matlab">
hFig = figure('Color','w');

% 1. controllib.widget.Slider
hSlider1 = controllib.widget.Slider(hFig, [10,10,100,50], 1:20);
hSlider1.Value = 12;

% 2. uicontrol
hSlider2 = uicontrol('style','slider', 'units','pixels', 'pos',[10,80,100,20], 'Min',0', 'Max',20, 'Value',12);

% 3. JScrollBar
jSlider3 = javaObjectEDT(javax.swing.JScrollBar);
jSlider3.setOrientation(jSlider3.HORIZONTAL);  % Java setter-method notation
set(jSlider3, 'VisibleAmount',1, 'Minimum',0, 'Maximum',20, 'Value',12);  % HG set notation
[hSlider3, hContainer3] = javacomponent(jSlider3, [10,130,100,20], hFig);

% 4. JSlider #1
jSlider4 = javaObjectEDT(javax.swing.JSlider(0,20,12))
jSlider4.setBackground(java.awt.Color.white);  % Java setter-method notation
set(jSlider4, 'MinorTickSpacing',1, 'MajorTickSpacing',4, 'SnapToTicks',true, 'PaintLabels',true);  % HG set notation
[hSlider4, hContainer4] = javacomponent(jSlider4, [10,180,100,30], hFig);

% 5. JSlider #2
jSlider5 = javaObjectEDT(javax.swing.JSlider(0,20,12))
jSlider5.setBackground(java.awt.Color.white);  % Java setter-method notation
jSlider5.setPaintTicks(true);
set(jSlider5, 'MinorTickSpacing',1, 'MajorTickSpacing',4, 'SnapToTicks',true, 'PaintLabels',true);  % HG set notation
[hSlider5, hContainer5] = javacomponent(jSlider5, [10,230,100,40], hFig);
</pre>
<p>For additional details regarding the other slider alternatives, please refer to <a href="/articles/sliders-in-matlab-gui" target="_blank">my earlier post</a> on this subject.<br />
Have you ever used another interesting utility or class in Matlab&#8217;s builtin packages? If so, please tell us about it in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2">Sliders in Matlab GUI &#8211; part 2</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/sliders-in-matlab-gui" rel="bookmark" title="Sliders in Matlab GUI">Sliders in Matlab GUI </a> <small>Professional-looking slider controls can easily be integrated in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>String/char compatibility</title>
		<link>https://undocumentedmatlab.com/articles/string-char-compatibility?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=string-char-compatibility</link>
					<comments>https://undocumentedmatlab.com/articles/string-char-compatibility#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 28 Jun 2018 12:57:59 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7710</guid>

					<description><![CDATA[<p>Backward compatibility of strings in function inputs is a challenge, that can be assisted with an undocumented builtin  function. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/string-char-compatibility">String/char compatibility</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/sliders-in-matlab-gui-part-2" rel="bookmark" title="Sliders in Matlab GUI &#8211; part 2">Sliders in Matlab GUI &#8211; part 2 </a> <small>Matlab contains a variety of ways to define/display slider controls in GUI windows. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/ismembc-undocumented-helper-function" rel="bookmark" title="ismembc &#8211; undocumented helper function">ismembc &#8211; undocumented helper function </a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In numerous functions that I wrote over the years, some input arguments were expected to be strings in the old sense, i.e. char arrays for example, <code>'on'</code> or <code>'off'</code>. Matlab release R2016b introduced the concept of <a href="https://www.mathworks.com/help/matlab/characters-and-strings.html" rel="nofollow" target="_blank">string objects</a>, which can be created using the <i><b>string</b></i> function or [starting in R2017a] double quotes (<code>"on"</code>).<br />
The problem is that I have numerous functions that supported the old char-based strings but not the new string objects. If someone tries to enter a string object (<code>"on"</code>) as input to a function that expects a char-array (<code>'on'</code>), in many cases Matlab will error. This by itself is very unfortunate &#8211; I would have liked everything to be fully backward-compatible. But unfortunately this is not the case: MathWorks did invest effort in making the new strings backward-compatible to some degree (for example, graphic object property names/values and many internal functions that now accept either form as input). However, backward compatibility of strings is not 100% perfect.<br />
In such cases, the only solution is to make the function accept both forms (char-arrays and string objects), for example, by type-casting all such inputs as char-arrays using the builtin <i><b>char</b></i> function. If we do this at the top of our function, then the rest of the function can remain unchanged. For example:<br />
<span id="more-7710"></span></p>
<pre lang="matlab" highlight="2-4">
function test(stage)
   if isa(stage,'string')
      stage = char(stage);
   end
   % from this point onward, we don't need to worry about string inputs - any such strings will become plain-ol' char-arrays
   switch stage
      case 'stage 1', ...
      case 'stage 2', ...
      ...
   end
end
</pre>
<p>That was simple enough. But what if our function expects complex inputs (cell-arrays, structs etc.) that may contain strings in only some of their cells/fields?<br />
Luckily, Matlab contains an internal utility function that can help us: <i><b>controllib.internal.util.hString2Char</b></i>. This function, whose Matlab source-code is available (<i>%matlabroot%/toolbox/shared/controllib/general/+controllib/+internal/+util/hString2Char.m</i>) recursively scans the input value and converts any string object into the corresponding char-array, leaving all other data-types unchanged. For example:</p>
<pre lang="matlab">
>> controllib.internal.util.hString2Char({123, 'char-array', "a string"})
ans =
  1×3 cell array
    {[123]}    {'char-array'}    {'a string'}
>> controllib.internal.util.hString2Char(struct('a',"another string", 'b',pi))
ans =
  struct with fields:
    a: 'another string'
    b: 3.14159265358979
</pre>
<p>In order to keep our code working not just on recent releases (that support strings and <i><b>controllib.internal.util.hString2Char</b></i>) but also on older Matlab releases (where they did not exist), we simply wrap the call to <i><b>hString2Char</b></i> within a <i><b>try</b></i>&#8211;<i><b>catch</b></i> block. The adaptation of our function might then look as follows:</p>
<pre lang="matlab" highlight="2">
function test(varargin)
   try varargin = controllib.internal.util.hString2Char(varargin); catch, end
   % from this point onward, we don't need to worry about string inputs - any such strings will become plain-ol' char-arrays
   ...
end
</pre>
<p>Note that <i><b>controllib.internal.util.hString2Char</b></i> is a semi-documented function: it contains a readable internal help section (accessible via <code>help controllib.internal.util.hString2Char</code>), but not a doc-page. Nor is this function mentioned anywhere in Matlab&#8217;s official documentation. I think that this is a pity, because it&#8217;s such a useful little helper function.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/string-char-compatibility">String/char compatibility</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/sliders-in-matlab-gui-part-2" rel="bookmark" title="Sliders in Matlab GUI &#8211; part 2">Sliders in Matlab GUI &#8211; part 2 </a> <small>Matlab contains a variety of ways to define/display slider controls in GUI windows. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/ismembc-undocumented-helper-function" rel="bookmark" title="ismembc &#8211; undocumented helper function">ismembc &#8211; undocumented helper function </a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/string-char-compatibility/feed</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
			</item>
		<item>
		<title>Password &#038; spinner controls in Matlab GUI</title>
		<link>https://undocumentedmatlab.com/articles/password-and-spinner-controls-in-matlab-gui?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=password-and-spinner-controls-in-matlab-gui</link>
					<comments>https://undocumentedmatlab.com/articles/password-and-spinner-controls-in-matlab-gui#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 14 Dec 2016 17:28:09 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6775</guid>

					<description><![CDATA[<p>Password fields and spinner controls can easily be embedded in Matlab GUIs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/password-and-spinner-controls-in-matlab-gui">Password &amp; spinner controls in Matlab GUI</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/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" rel="bookmark" title="Using spinners in Matlab GUI">Using spinners in Matlab GUI </a> <small>Spinner controls can easily be added to Matlab GUI. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" rel="bookmark" title="Reverting axes controls in figure toolbar">Reverting axes controls in figure toolbar </a> <small>In R2018b the axes controls were removed from the figure toolbar, but this can be reverted. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I often include configuration panels in my programs, to enable the user to configure various program aspects, such as which emails should automatically be sent by the program to alert when certain conditions occur. Last week <a href="/articles/sending-email-text-messages-from-matlab" target="_blank">I presented</a> such a configuration panel, which is mainly composed of standard documented Matlab controls (sub-panels, uitables and uicontrols). As promised, today&#8217;s post will discuss two undocumented controls that are often useful in similar configuration panels (not necessarily for emails): password fields and spinners.<br />
<center><a href="/images/email_config_panel.png" target="_blank"><img decoding="async" alt="Matlab GUI configuration panel including password and spinner controls (click to zoom-in)" src="https://undocumentedmatlab.com/images/email_config_panel.png" title="Matlab GUI configuration panel including password and spinner controls (click to zoom-in)" width="75%" style="max-width:842px;"></a><br />
Matlab GUI configuration panel including password and spinner controls (click to zoom-in)</center><br />
Password fields are basically editboxes that hide the typed text with some generic echo character (such as * or a bullet); spinners are editboxes that only enable typing certain preconfigured values (e.g., numbers in a certain range). Both controls are part of the standard Java Swing package, on which the current (non-web-based) Matlab GUIs relies. In both cases, we can use the <a href="/articles/javacomponent" target="_blank"><i><b>javacomponent</b></i> function</a> to place the built-in Swing component in our Matlab GUI.<br />
<span id="more-6775"></span></p>
<h3 id="password">Password field</h3>
<p>The relevant Java Swing control for password fields is <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html"><code>javax.swing.JPasswordField</code></a>. <code>JPasswordField</code> is basically an editbox that hides any typed key with a * or bullet character.<br />
Here&#8217;s a basic code snippet showing how to display a simple password field:</p>
<pre lang='matlab'>
jPasswordField = javax.swing.JPasswordField('defaultPassword');  % default password arg is optional
jPasswordField = javaObjectEDT(jPasswordField);  % javaObjectEDT is optional but recommended to avoid timing-related GUI issues
jhPasswordField = javacomponent(jPasswordField, [10,10,70,20], gcf);
</pre>
<p><center><figure style="width: 105px" class="wp-caption aligncenter"><img decoding="async" alt="Password control" src="https://undocumentedmatlab.com/images/JPasswordField.gif" title="Password control" width="105" height="30" /><figcaption class="wp-caption-text">Password control</figcaption></figure></center><br />
We can set/get the password string programmatically via the <b>Text</b> property; the displayed (echo) character can be set/get using the <b>EchoChar</b> property.<br />
To attach a data-change callback, set jhPasswordField&#8217;s <b>ActionPerformedCallback</b> property.</p>
<h3 id="spinner">Spinner control</h3>
<p><a href="/articles/using-spinners-in-matlab-gui" target="_blank">detailed post on using spinners in Matlab GUI</a><br />
The relevant Java Swing control for spinners is <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html"><code>javax.swing.JSpinner</code></a>. <code>JSpinner</code> is basically an editbox with two tiny adjacent up/down buttons that visually emulate a small round spinning knob. Spinners are similar in functionality to a combo-box (a.k.a. drop-down or pop-up menu), where a user can switch between several pre-selected values. They are often used when the list of possible values is too large to display in a combo-box menu. Like combo-boxes, spinners too can be editable (meaning that the user can type a value in the editbox) or not (the user can only &#8220;spin&#8221; the value using the up/down buttons).<br />
<code>JSpinner</code> uses an internal data model. The default model is <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/SpinnerNumberModel.html"><code>SpinnerNumberModel</code></a>, which defines a min/max value (unlimited=[] by default) and step-size (1 by default). Additional predefined models are <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/SpinnerListModel.html"><code>SpinnerListModel</code></a> (which accepts a cell array of possible string values) and <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/SpinnerDateModel.html"><code>SpinnerDateModel</code></a> (which defines a date range and step unit).<br />
Here&#8217;s a basic code snippet showing how to display a simple numeric spinner for numbers between 20 and 35, with an initial value of 24 and increments of 0.1:</p>
<pre lang='matlab'>
jModel = javax.swing.SpinnerNumberModel(24,20,35,0.1);
jSpinner = javax.swing.JSpinner(jModel);
jSpinner = javaObjectEDT(jSpinner);  % javaObjectEDT is optional but recommended to avoid timing-related GUI issues
jhSpinner = javacomponent(jSpinner, [10,10,70,20], gcf);
</pre>
<p>The spinner value can be set using the edit-box or by clicking on one of the tiny arrow buttons, or programmatically by setting the <b>Value</b> property. The spinner object also has related read-only properties <b>NextValue</b> and <b>PreviousValue</b>. The spinner&#8217;s model object has the corresponding <b>Value</b> (settable), <b>NextValue</b> (read-only) and <b>PreviousValue</b> (read-only) properties. In addition, the various models have specific properties. For example, <code>SpinnerNumberModel</code> has the settable <b>Maximum</b>, <b>Minimum</b> and <b>StepSize</b> properties.<br />
To attach a data-change callback, set jhSpinner&#8217;s <b>StateChangedCallback</b> property.<br />
I have created a small Matlab demo, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26970-spinnerdemo"><i><b>SpinnerDemo</b></i></a>,  which demonstrates usage of <code>JSpinner</code> in Matlab figures. Each of the three predefined models (number, list, and date) is presented, and the spinner values are inter-connected via their callbacks. The Matlab code is modeled after the <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/examples/components/SpinnerDemoProject/src/components/SpinnerDemo.java">Java code</a> that is used to document <code>JSpinner</code> in the official Java documentation. Readers are welcome to download this demo from the Matlab File Exchange and reuse its source code.<br />
<center><figure style="width: 188px" class="wp-caption aligncenter"><img decoding="async" alt="Matlab SpinnerDemo" src="https://undocumentedmatlab.com/images/SpinnerDemoMatlab.png" title="Matlab SpinnerDemo" width="188" height="184"/><figcaption class="wp-caption-text">Matlab SpinnerDemo</figcaption></figure></center><br />
The nice thing about spinners is that you can set a custom display format without affecting the underlying data model. For example, the following code snippet update the spinner&#8217;s display format without affecting its underlying numeric data model:</p>
<pre lang="matlab">
formatStr = '$ #,##0.0 Bn';
jEditor = javaObject('javax.swing.JSpinner$NumberEditor', jhSpinner, formatStr);
jhSpinner.setEditor(jEditor);
</pre>
<p><center><figure style="width: 105px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Formatted spinner control" src="https://undocumentedmatlab.com/images/JSpinner.gif" title="Formatted spinner control" width="105" height="30" /><figcaption class="wp-caption-text">Formatted spinner control</figcaption></figure></center><br />
For more information, refer to my <a href="/articles/using-spinners-in-matlab-gui" target="_blank">detailed post on using spinners in Matlab GUI</a>.</p>
<h3 id="warning">Caveat emptor</h3>
<p>MathWorks&#8217; new web-based GUI paradigm will most probably not directly support the Java components presented in today&#8217;s post, or more specifically the <i><b>javacomponent</b></i> function that enables placing them in Matlab GUIs. The new web-based GUI-building application (<a href="https://www.mathworks.com/products/matlab/app-designer.html" rel="nofollow" target="_blank">AppDesigner</a>, aka AD) does contain a spinner, although it is [currently] limited to displaying numeric values (not dates/lists as in my SpinnerDemo). Password fields are not currently supported by AppDesigner at all, and it is unknown whether they will ever be.<br />
All this means that users of Java controls who wish to transition to the new web-based GUIs will need to develop <a href="/articles/editbox-data-input-validation" rel="nofollow" target="_blank">programmatic workarounds</a>, that would presumably appear and behave less professional. It&#8217;s a tradeoff: AppDesigner does include features that improve GUI usability, not to mention the presumed future ability to post Matlab GUIs online (hopefully without requiring a monstrous Matlab Production Server license/installation).<br />
In the past, MathWorks has posted a <a href="http://www.mathworks.com/support/contact_us/dev/javaframe.html" rel="nofollow" target="_blank">dedicated webpage</a> to solicit user feedback on how they are using the figure&#8217;s <b>JavaFrame</b> property. MathWorks will presumably prepare a similar webpage to solicit user feedback on uses of the <i><b>javacomponent</b></i> function, so they could add the top items to AppDesigner, making the transition to web-based GUIs less painful. When such a survey page becomes live, I will post about it on this website so that you could tell MathWorks about your specific use-cases and help them prioritize their R&#038;D efforts.<br />
In any case, regardless of whether the functionality eventually makes it into AppDesigner, my hope is that when the time comes MathWorks will not pull the plug from non-web GUIs, and will still enable running them on desktops for backward compatibility (&#8220;legacy mode&#8221;). Users of existing GUIs will then not need to choose between upgrading their Matlab (and redeveloping their GUI as a web-based app) and running their existing programs. Instead, users will face the much less painful choice between keeping the existing Java-based programs and developing a web-based variant at some later time, separate from the choice of whether or not to upgrade Matlab. The increased revenue from license upgrades and SMS (maintenance plan) renewals might well offset the R&#038;D effort that would be needed to keep supporting the old Java-based figures. The traumatic<sup>*</sup> release of HG2 in R2014b, where a less-than-perfect version was released with no legacy mode, resulting in significant user backlash/disappointment, is hopefully still fresh in the memory of decision makers and would hopefully not be repeated.<br />
<sup>*</sup><i>well, traumatic for some at least. I really don&#8217;t wish to make this a debate on HG2&#8217;s release; I&#8217;d rather focus on making the transition to web-based GUIs as seamless as possible.</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/password-and-spinner-controls-in-matlab-gui">Password &amp; spinner controls in Matlab GUI</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/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" rel="bookmark" title="Using spinners in Matlab GUI">Using spinners in Matlab GUI </a> <small>Spinner controls can easily be added to Matlab GUI. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" rel="bookmark" title="Reverting axes controls in figure toolbar">Reverting axes controls in figure toolbar </a> <small>In R2018b the axes controls were removed from the figure toolbar, but this can be reverted. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/password-and-spinner-controls-in-matlab-gui/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Viewing saved profiling results</title>
		<link>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=viewing-saved-profiling-results</link>
					<comments>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 May 2016 18:00:37 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6421</guid>

					<description><![CDATA[<p>We can easily use saved profiling results to analyze, view and compare profiling results of multiple runs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/viewing-saved-profiling-results">Viewing saved profiling results</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/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="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/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Many Matlab users know and utilize <a href="http://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html" rel="nofollow" target="_blank">Matlab&#8217;s built-in Profiler tool</a> to identify performance bottlenecks and code-coverage issues. Unfortunately, not many are aware of the Profiler&#8217;s programmatic interface. In past articles as well as my performance book I <a href="/articles/undocumented-profiler-options-part-3" target="_blank">explained</a> how we can use this programmatic interface to save profiling results and analyze it offline. In fact, I took this idea further and even created a utility (<a href="/articles/function-call-timeline-profiling" target="_blank"><i><b>profile_history</b></i></a>) that displays the function call timeline in a standalone Matlab GUI, something that is a sorely missed feature in the built-in profiler:<br />
<center><a target="_blank" href="/images/profile_history.png"><img decoding="async" alt="Function call timeline profiling (click for full-size image)" src="https://undocumentedmatlab.com/images/profile_history.png" title="Function call timeline profiling (click for full-size image)" width="100%" style="max-width: 658px;" /></a><br />
Function call timeline profiling (click for full-size image)</center><br />
Today I will discuss a related undocumented feature of the Profiler: loading and viewing pre-saved profiling results.<br />
<span id="more-6421"></span></p>
<h3 id="output">Programmatic access to profiling results</h3>
<p>Matlab&#8217;s syntax for returning the detailed profiling results in a data struct is clearly documented in the <a href="http://www.mathworks.com/help/matlab/ref/profile.html#bux4pud-1" rel="nofollow" target="_blank"><i><b>profile</b></i> function&#8217;s doc page</a>. Although the documentation does not explain the resulting struct and sub-struct fields, they have meaningful names and we can relatively easily infer what each of them means (I added a few annotation comments for clarity):</p>
<pre lang="matlab">
>> profile('on','-history')
>> surf(peaks); drawnow
>> profile('off')
>> profData = profile('info')
profData =
      FunctionTable: [26x1 struct]
    FunctionHistory: [2x56 double]
     ClockPrecision: 4.10517962829241e-07
         ClockSpeed: 2501000000
               Name: 'MATLAB'
           Overhead: 0
>> profData.FunctionTable(1)
ans =
          CompleteName: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\specgraph\peaks.m>peaks'
          FunctionName: 'peaks'
              FileName: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\specgraph\peaks.m'
                  Type: 'M-function'
              Children: [1x1 struct]
               Parents: [0x1 struct]
         ExecutedLines: [9x3 double]
           IsRecursive: 0
    TotalRecursiveTime: 0
           PartialData: 0
              NumCalls: 1
             TotalTime: 0.0191679078068094
>> profData.FunctionTable(1).Children
ans =
        Index: 2   % index in profData.FunctionTable array
     NumCalls: 1
    TotalTime: 0.00136415141013509
>> profData.FunctionTable(1).ExecutedLines   % line number, number of calls, duration in secs
ans =
         43      1      0.000160102031282782
         44      1      2.29890096200918e-05
         45      1      0.00647592190637408
         56      1      0.0017093970724654
         57      1      0.00145036019621044
         58      1      0.000304193859437286
         60      1      4.39254290955326e-05
         62      1      3.44835144301377e-05
         63      1      0.000138755093778411
>> profData.FunctionHistory(:,1:5)
ans =
     0     0     1     1     0   % 0=enter, 1=exit
     1     2     2     1     6   % index in profData.FunctionHistory array
</pre>
<p>As we can see, this is pretty intuitive so far.</p>
<h3 id="viewing">Loading and viewing saved profiling results</h3>
<p>If we wish to save these results results in a file and later load and display them in the Profiler&#8217;s visualization browser, then we need to venture deeper into undocumented territory. It seems that while retrieving the profiling results (via <i><b>profile</b>(&#8216;info&#8217;)</i>) is fully documented, doing the natural complementary action (namely, loading this data into the viewer) is not. For the life of me I cannot understand the logic behind this decision, but that&#8217;s the way it is.<br />
Luckily, the <a href="/articles/legend-semi-documented-feature#Semi-documented" target="_blank">semi-documented built-in function</a> <i><b>profview</b></i> does exactly what we need: <i><b>profview</b></i> accepts 2 input args (function name and the <code>profData</code> struct) and displays the resulting profiling info. The first input arg (function name) accepts either a string (e.g., <code>'peaks'</code> or <code>'view>isAxesHandle'</code>), or the numeric value 0 which signifies the home (top-level) page:</p>
<pre lang="matlab">
profView(0, profData);  % display profiling home (top-level) page
profview('peaks', profData);  % display a specific profiling page
</pre>
<p>I use the 0 input value much more frequently than the string inputs, because I often don&#8217;t know which functions exactly were profiled, and starting at the home page enables me to easily drill-down the profiling results interactively.</p>
<h3 id="viewing">Loading saved profiling results from a different computer</h3>
<p>Things get slightly complicated if we try to load saved profiling results from a different computer. If the other computer has exactly the same folder structure as our computer, and all our Matlab functions reside in exactly the same disk folders/path, then everything will work out of the box. The problem is that in general the other computer will have the functions in different folders. When we then try to load the <code>profData</code> on our computer, it will not find the associated Matlab functinos in order to display the line-by-line profiling results. We will only see the profiling data at the function level, not line level. This significantly reduces the usefulness of the profiling data. The Profiler page will display the following error message:<br />
<center><span style="background: #FFC0C0;"><code>This file was modified during or after profiling. Function listing disabled.</code></span></center><br />
We can solve this problem in either of two ways:</p>
<ol>
<li>Modify our <code>profData</code> to use the correct folder path on the local computer, rather than the other computer&#8217;s path (which is invalid on the local computer). For example:
<pre lang="matlab">
% Save the profData on computer #1:
profData = profile('info');
save('profData.mat', 'profData');
% Load the profData on computer #2:
fileData = load('profData.mat');
profData = fileData.profData;
path1 = 'N:\Users\Juan\programs\myProgram';
path2 = 'C:\Yair\consulting\clients\Intel\code';
for idx = 1 : numel(profData.FunctionTable)
   funcData = profData.FunctionTable(idx);
   funcData.FileName     = strrep(funcData.FileName,     path1, path2);
   funcData.CompleteName = strrep(funcData.CompleteName, path1, path2);
   profData.FunctionTable(idx) = funcData;
end
% note: this loop can be vectorized if you wish
</pre>
</li>
<li>As an alternative, we can modify Matlab&#8217;s <i>profview.m</i> function (<i>%matlabroot%/toolbox/matlab/codetools/profview.m</i>) to search for the function&#8217;s source code in the current Matlab path, if the specified direct path is not found (note that changing <i>profview.m</i> may require administrator priviledges). For example, the following is the code from R2016a&#8217;s <i>profview.m</i> file, line #506:
<pre lang="matlab" highlight="3-5,7-9">
    % g894021 - Make sure the MATLAB code file still exists
    if ~exist(fullName, 'file')
        [~,fname,fext] = fileparts(fullName);  % Yair
        fname = which([fname fext]);           % Yair
        if isempty(fname)                      % Yair
            mFileFlag = 0;
        else                                   % Yair
            fullName = fname;                  % Yair
        end                                    % Yair
    end
</pre>
</li>
</ol>
<p>These two workarounds complement each other: the first workaround does not require changing any installed Matlab code, and so is platform- and release-independent, but would require rerunning the code snippet for each and every profiling data file that we receive from external computers. On the other hand, the second workaround is a one-time operation that should work for multiple saved profiling results, although we would need to redo it whenever we install Matlab.</p>
<h3 id="customizations">Additional <i><b>profview</b></i> customizations</h3>
<p>Modifying the <i>profview.m</i> function can be used for different improvements as well.<br />
For example, several years ago <a href="/articles/undocumented-profiler-options-part-2" target="_blank">I explained</a> how this function can be modified to display 1 ms timing resolutions, rather than the default 10 mS.<br />
Another customization that I often do after I install Matlab is to change the default setting of truncating function lines longer than 40 characters &#8211; I typically modify this to 60 or 80 (depending on the computer monitor&#8217;s size&#8230;). All we need to do is to update the <code>truncateDisplayName</code> sub-function within <i>profview.m</i> as follows (taken from R2016a again, line #1762):</p>
<pre lang="matlab" highlight="3">
function shortFileName = truncateDisplayName(longFileName,maxNameLen)
%TRUNCATEDISPLAYNAME  Truncate the name if it gets too long
maxNameLen = max(60,maxNameLen);  % Yair
shortFileName = escapeHtml(longFileName);
if length(longFileName) > maxNameLen,
    shortFileName = char(com.mathworks.util.FileUtils.truncatePathname( ...
        shortFileName, maxNameLen));
end
</pre>
<p>You can see additional undocumented profiling features in the &#8220;Related posts&#8221; section below, as well as in Chapter 2 of my book &#8220;<a href="/books/matlab-performance" target="_blank"><i>Accelerating MATLAB Performance</i></a>&#8220;.<br />
Do you have any other customization to the profiling results? If so, please share it in a comment.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/viewing-saved-profiling-results">Viewing saved profiling results</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/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="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/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Editable combo-box</title>
		<link>https://undocumentedmatlab.com/articles/editable-combo-box?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=editable-combo-box</link>
					<comments>https://undocumentedmatlab.com/articles/editable-combo-box#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 Oct 2013 15:38:55 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4246</guid>

					<description><![CDATA[<p>Matlab's popup menu (combo-box) control is quite limited in its abilities. This article explains how we can work around these limitations. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/editable-combo-box">Editable combo-box</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/using-jide-combo-boxes" rel="bookmark" title="Using JIDE combo-boxes">Using JIDE combo-boxes </a> <small>Matlab includes many custom JIDE combo-box controls that can be used in Matlab GUIs out of the box. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/common-javacomponent-problems" rel="bookmark" title="Common javacomponent problems">Common javacomponent problems </a> <small>The javacomponent function is very useful for placing Java components on-screen, but has a few quirks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In previous articles, I explained how we can use <a target="_blank" href="/articles/findjobj-find-underlying-java-object/"><i><b>findjobj</b></i></a> to customize a Matlab uicontrol&#8217;s underlying Java control, thereby improving its appearance and functionality. My two previous <a target="_blank" href="/articles/customizing-editboxes/">articles</a> on the Matlab editbox were a classic example of this mechanism. Unfortunately, this technique does not always work well, and an alternative mechanism needs to be used. One such case in point is the subject of today&#8217;s article.<br />
Matlab combo-box (a.k.a. &#8220;popup-menu&#8221; or &#8220;drop-down&#8221;) controls are very simple controls that accept a list of strings from which a user can select. This is a very simple control that answers a wide range of use-cases. Unfortunately, it is quite limited. Among other limitations, we cannot modify the popup-panel&#8217;s appearance/functionality; we cannot select multiple items; and we cannot type-in a value in the control&#8217;s editbox. Today&#8217;s article will focus on the latter limitation, namely how to use an editable combo-box.</p>
<h3 id="standard">Trying to make Matlab&#8217;s standard combobox editable</h3>
<p>We can indeed use <i><b>findjobj</b></i> to get a Matlab combo-box&#8217;s underlying Java control. This turns out to be a <code>com.mathworks.hg.peer.ComboboxPeer$MLComboBox</code> object, which extends the standard Java Swing <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html">JComboBox</a>:</p>
<pre lang='matlab'>
>> hCombo = uicontrol('Style','popup', 'String',{'a','b','c'});
>> jCombo = findjobj(hCombo)
jCombo =
	javahandle_withcallbacks.com.mathworks.hg.peer.ComboboxPeer$MLComboBox
</pre>
<p>This <code>jCombo</code> control has the <b>Editable</b> property that we can then try to override (the default value is <code>false</code>):</p>
<pre lang='matlab'>
>> jCombo.setEditable(true);
>> jCombo.Editable = true;          % equivalent alternative
>> set(jCombo,'setEditable',true);  % equivalent alternative
</pre>
<p><figure style="width: 98px" class="wp-caption alignleft"><img loading="lazy" decoding="async" alt="Editable combo-box control" src="https://undocumentedmatlab.com/images/combobox_editable.png" title="Editable combo-box control" width="98" height="75" /><figcaption class="wp-caption-text">Editable combo-box control</figcaption></figure><br />
The bad news is that the moment we enter some value (as in the screenshot here) that is not already a member of the pop-up panel (i.e., the cell-array in the <b>String</b> property), then the control disappears and a warning message is issued to the Matlab console:</p>
<pre lang='matlab'>
Warning: popupmenu control requires that Value be an integer within String range
Control will not be rendered until all of its parameter values are valid
(Type "warning off MATLAB:hg:uicontrol:ParameterValuesMustBeValid" to suppress this warning.)
</pre>
<p><span id="more-4246"></span><br />
The reason for this behavior is that when the combo-box object detects that the text field&#8217;s content match none of the popup list items, it automatically sets <code>jCombo</code>&#8216;s <b>SelectedIndex</b> to -1 and Matlab&#8217;s corresponding HG <b>Value</b> property to 0. At this point the Matlab implementation kicks in, hiding the uicontrol since it considers 0 an invalid value for the <b>Value</b> property. This is similar to the check being done to test for an empty HG String value (=no items):</p>
<pre lang='matlab'>
>> set(hCombo, 'string', [])
popupmenu control requires a non-empty String
Control will not be rendered until all of its parameter values are valid.
</pre>
<p>We can clear these particular warnings via:</p>
<pre lang='matlab'>warning('off','MATLAB:hg:uicontrol:ParameterValuesMustBeValid')</pre>
<p>but this does not prevent the control from being hidden – it just prevents the warning from showing on the Command Window.<br />
We can dive deeper and try to modify the underlying data model and disassociate the Java control from HG, but let&#8217;s stop at this point since there is really no point considering the fact that there is a much simpler alternative.<br />
Note: if you do decide to make the standard Matlab uicontrol editable, read <a target="_blank" href="/articles/additional-uicontrol-tooltip-hacks/#truncated_text">here</a> for a related customization that I posted several years ago.</p>
<h3 id="Java">The pure-Java alternative</h3>
<p>Rather than customizing Matlab&#8217;s uicontrol, we can easily create an identical-looking control using the standard Java Swing JComboBox, which has none of these problems/limitations. We can create and display the component in one go using the semi-documented <a target="_blank" href="/articles/javacomponent/"><i><b>javacomponent</b></i></a> function:</p>
<pre lang='matlab' highlight='5,6'>
position = [10,100,90,20];  % pixels
hContainer = gcf;  % can be any uipanel or figure handle
options = {'a','b','c'};
model = javax.swing.DefaultComboBoxModel(options);
jCombo = javacomponent('javax.swing.JComboBox', position, hContainer);
jCombo.setModel(model);
jCombo.setEditable(true);
</pre>
<p>We can use a variant of <i><b>javacomponent</b></i> to create the component with the model in one go, replacing the highlighted lines above:</p>
<pre lang='matlab'>jCombo = javacomponent({'javax.swing.JComboBox',model}, position, hContainer);</pre>
<p>Once we have the control ready, all we need to do is set its <b>ActionPerformedCallback</b> property to our Matlab callback function and we&#8217;re pretty-much set. We can get the currently-selected text using <code>char(jCombo.getSelectedItem)</code> and the selected list index (0-based) using <code>jCombo.getSelectedIndex</code> (which returns -1 if we entered a non-listed value, 0 for the first list item, 1 for the second etc.). More information can be found <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html">here</a>.</p>
<h3 id="conclusion">Lesson learnt</h3>
<p>In the past 20+ years of my professional life as engineer and development manager, my number one rule <a target="_blank" href="/articles/xlsread-functionality-change-in-r2012a/">has always been</a>:<br />
<center><font size=+3 color="red"><i><b>DON&#8217;T FIX IT, IF IT AIN&#8217;T BROKE!</b></i></font></center><br />
But sometimes, we should also remember an alternative version:<br />
<center><font size=+3 color="red"><i><b>DON&#8217;T FIX IT, IF IT&#8217;S EASIER TO REPLACE!</b></i></font></center></p>
<h3 id="report">Available report &#8211; &#8220;Advanced Customizations of Matlab Uicontrols&#8221;</h3>
<p>Interested readers can find more information about these and other possible customizations in my report on &#8220;<i>Advanced Customizations of Matlab Uicontrols</i>&#8220;. This 90-page PDF report can be purchased <a target="_blank" rel="nofollow" href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=altmany@gmail.com&#038;amount=29&#038;item_name=Matlab+uicontrols+customization+report">here</a> ($29, please allow 24 hours for delivery by email). The report explains how to customize Matlab&#8217;s uicontrols in ways that are simply not possible using documented Matlab properties. This includes treatment of push buttons, toggle buttons, radio buttons, checkboxes, editboxes, listboxes, popup menus (aka combo-boxes/drop-downs), sliders, labels, and tooltips. Much of the information in the report is also available in hard-copy format in chapter 6 of my <a target="_blank" href="/matlab-java-book/">Matlab-Java programming book</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/editable-combo-box">Editable combo-box</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/using-jide-combo-boxes" rel="bookmark" title="Using JIDE combo-boxes">Using JIDE combo-boxes </a> <small>Matlab includes many custom JIDE combo-box controls that can be used in Matlab GUIs out of the box. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/common-javacomponent-problems" rel="bookmark" title="Common javacomponent problems">Common javacomponent problems </a> <small>The javacomponent function is very useful for placing Java components on-screen, but has a few quirks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/editable-combo-box/feed</wfw:commentRss>
			<slash:comments>20</slash:comments>
		
		
			</item>
		<item>
		<title>Function definition meta-info</title>
		<link>https://undocumentedmatlab.com/articles/function-definition-meta-info?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=function-definition-meta-info</link>
					<comments>https://undocumentedmatlab.com/articles/function-definition-meta-info#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 04 Sep 2013 13:38:42 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4141</guid>

					<description><![CDATA[<p>There are multiple ways to retrieve meta-info about functions in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/function-definition-meta-info">Function definition meta-info</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/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</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/math-libraries-version-info-upgrade" rel="bookmark" title="Math libraries version info &amp; upgrade">Math libraries version info &amp; upgrade </a> <small>Matlab exposes undocumented info about its internal math libraries; these libraries can be upgraded manually. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/javacomponent" rel="bookmark" title="The javacomponent function">The javacomponent function </a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week, Loren Shure <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab-file-is-this/">posted an article</a> explaining some documented ways to retrieve information about the type of Matlab functions. Loren basically showed how we can use a combination of the built-in <i><b>nargin</b></i> and <i><b>exist</b></i> functions to check whether a specified function-name is a regular m-file, a script filename, a class name or something else.<br />
Today I will discuss several additional alternatives for retrieving information about a specified function:</p>
<ul>
<li><a href="/articles/function-definition-meta-info/#mtree"><i><b>mtree</b></i></a></li>
<li><a href="/articles/function-definition-meta-info/#getcallinfo"><i><b>getcallinfo</b></i></a></li>
<li><a href="/articles/function-definition-meta-info/#mlint"><i><b>mlint</b></i></a></li>
<li><a href="/articles/function-definition-meta-info/#which"><i><b>which</b></i></a></li>
<li><a href="/articles/function-definition-meta-info/#functions"><i><b>functions</b></i></a></li>
</ul>
<h3 id="mtree">The <i>mtree()</i> alternative</h3>
<p>Reader Mark Brown has <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab-file-is-this/#comment-38909">commented</a> about an alternative, using the semi-documented built-in function <i><b>mtree</b></i>:</p>
<pre lang='matlab'>
>> t = mtree('mtree.m','-file'); t.select(1).kind  % m-class file
ans =
CLASSDEF
>> t = mtree('profile.m','-file'); t.select(1).kind  % regular m-file function
ans =
FUNCTION
>> t = mtree('test.m','-file'); t.select(1).kind  % script file
ans =
EXPR
</pre>
<p><i><b>mtree</b></i> contains numerous other goodies in its reported parse-tree, including information about who-calls-what-where, set/used info about variables and other information used in the lexical parsing of the m-file. <i><b>mtree</b></i> is a very sophisticated m-file function (or rather, a class), but is very heavily documented internally, and so it can definitely be read and followed. Unfortunately, much of the internal processing is carried out by opaque internal c-functions (<i>mtreemex</i>), but there is still plenty of processing left for the 3K+ lines of m-code. I plan to write an extensive article about this function one day.<br />
Unlike many other internal m-files, which are much simpler, less well written and sparsely documented (if at all), but for which personal credit is included in a comment, <i><b>mtree</b></i> includes no personal credit although it appears to be very well written and documented. I have to congratulate the unknown author(s) for both their proficiency and humility. <b><u>Addendum</u></b>: This unknown author is now confirmed to have been <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Stephen_C._Johnson">Steve Johnson</a>, author of the <a target="_blank" href="/articles/parsing-mlint-code-analyzer-output/">mlint</a> set of tools and functionality.<br />
For people worried about future compatibility, note that <i><b>mtree</b></i> has existed on the Matlab path (%matlabroot%\toolbox\matlab\codetools\@mtree\mtree.m) since 2006 (I think R2006a, but I&#8217;m not certain; it already had version 1.3 by R2007b; the latest version [R2013b] is 2.5). Considering the large investment in its code thus far, and the significant effort that it would take to create a replacement, I don&#8217;t see this function going away in the near future. Then again, there is no certainty about this, and it might well disappear without notice in some future Matlab release.</p>
<h3 id="getcallinfo">The <i>getcallinfo()</i> alternative</h3>
<p><i><b>getcallinfo</b></i> is another semi-documented internal function, which uses <i><b>mtree</b></i> to construct an m-file&#8217;s call-tree and reports the results in either a tabulated manner (if no output arg is request), or a struct array (as output arg):<br />
<span id="more-4141"></span></p>
<pre lang='java'>
>> getcallinfo('profile.m');
Name           Type             Starts Ends Length Full Name
----           ----             ------ ---- ------ ---------
profile        function             1   242    242 profile
ParseInputs    subfunction        247   354     82 profile>ParseInputs
ParseOption    nested-function    262   287     26 profile>ParseInputs/ParseOption
notifyUI       subfunction        356   370     15 profile>notifyUI
>> s = getcallinfo('profile.m')
s =
1x4 struct array with fields:
    type
    name
    fullname
    functionPrefix
    calls
    firstline
    lastline
    linemask
>> s(4).calls
ans =
      fcnCalls: [1x1 struct]
    innerCalls: [1x1 struct]
      dotCalls: [1x1 struct]
       atCalls: [1x1 struct]
>> s(4).calls.fcnCalls
ans =
    names: {'usejava'}
    lines: 359
>> s(4).calls.innerCalls
ans =
    names: {1x0 cell}
    lines: [1x0 double]
>> s(4).calls.dotCalls
ans =
    names: {'com.mathworks.mde.profiler.Profiler.start'  [1x40 char]  [1x41 char]}
    lines: [363 365 367]
</pre>
<p>Note: In order to use <i><b>getcallinfo</b></i>, we first need to fix a small internal bug in <i>%matlabroot%/toolbox/matlab/codetools/getcallinfo.m</i>, specifically within the <code>displayStructure()</code> sub-function. Modifying this file may require administrator privileges, and can be done in any text editor. The bug is that the keyword <code>length</code> is used as a variable in this function (line #136 in R2013b), and so cannot be used to reference the built-in function <i><b>length()</b></i>. We can either rename the variable (lines 136, 139, 145) or the function. It&#8217;s easiest to rename <i><b>length()</b></i> to <i><b>numel()</b></i> in line #147 (highlighted below):</p>
<pre lang='matlab' highlight='3,11'>
130:   function displayStructure(strc)
           ...
136:       length = getString(message('MATLAB:codetools:reports:RptLength'));
137:       fullName = getString(message('MATLAB:codetools:reports:RptFullName'));
138:
139:       fprintf('%-20s %-20s %-4s %-4s %-6s %-20s\n',name,type,starts,ends,length,fullName);
140:       fprintf('%-20s %-20s %-4s %-4s %-6s %-20s\n', ...
               ...
145:           getDashesForString(length), ...
146:           getDashesForString(fullName));
147:       for n = 1:numel(strc)   % original code: n = 1:length(strc)
               ...
152:       end
153:   end
</pre>
<h3 id="mlint">The <i>mlint()</i> alternative</h3>
<p>A few months ago, I <a target="_blank" href="/articles/parsing-mlint-code-analyzer-output/">wrote</a> about <i><b>mlint</b></i>&#8216;s undocumented interface and ability to report much internal information about the analyzed file. It is no surprise that one of the undocumented <i><b>mlint</b></i> options is <code>-calls</code>, which lists the calling-tree of an m-file. For example:</p>
<pre lang='matlab'>
>> mlint profile.m -calls
M0 1 14 profile
E0 242 3 profile
U1 122 15 callstats
U1 131 11 ParseInputs
U1 133 10 MException
U1 134 5 throw
U1 161 8 lower
U1 164 9 notifyUI
U1 165 23 true
U1 169 23 false
U1 180 9 profreport
U1 183 13 usejava
U1 184 13 error
U1 184 19 message
U1 188 21 profile
U1 189 16 isempty
U1 192 17 profview
U1 236 9 warning
S0 248 7 ParseInputs
E0 354 3 ParseInputs
U1 260 1 error
U1 260 7 nargchk
U1 260 17 Inf
U1 260 21 nargin
N1 262 23 ParseOption
E1 287 7 ParseOption
U2 263 12 strcmp
...
</pre>
<p>In this report, the first character represents the function type:</p>
<ul>
<li>M = main (top-level) function</li>
<li>S = sub-function</li>
<li>N = nested function</li>
<li>U = out-of-scope (external/built-in) function</li>
<li>A = anonymous function</li>
<li>E = end-of-function indication</li>
</ul>
<p>The following numbers indicate the nesting level, line #, column # and function identifier (name). In essence, it&#8217;s the same information presented by <i><b>getcallinfo</b></i>, with two distinctions: <i><b>getcallinfo</b></i>&#8216;s report is much more nicely formatted, and on the other hand <i><b>getcallinfo</b></i> does not include internal function-calls (maybe there&#8217;s an undocumented switch that I haven&#8217;t found for this).<br />
In this regard, I wish to once again praise Urs Schwartz&#8217;s excellent <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15924-farg-a-pedestrian-m-file-parser-showing-all-used-functions-syntax"><i><b>farg</b></i></a> and <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17291-fdep-a-pedestrian-function-dependencies-finder"><i><b>fdep</b></i></a> utilities, which use this undocumented <i><b>mlint</b></i> syntax. They seem to out-perform and out-class the built-in <i><b>depends</b></i> function by a wide margin&#8230;</p>
<h3 id="which">The <i>which()</i> alternative</h3>
<p>The built-in <i><b>which</b></i> function can be used to report the file-path of m-file functions, or an indicate that the function is built-in (i.e., coded as a C/C++ function in one of the Matlab libraries):</p>
<pre lang='matlab'>
>> str = which('perfTest')
str =
C:\Yair\Books\MATLAB Performance Tuning\Code\perfTest.m
>> str = which('matlab.io.MatFile')
str =
C:\Program Files\Matlab\R2013b\toolbox\matlab\iofun\+matlab\+io\MatFile.m
>> str = which('sin')
str =
built-in (C:\Program Files\Matlab\R2013b\toolbox\matlab\elfun\@double\sin)
>> str = which('noSuchFunction')
str =
     ''
</pre>
<p>Note: a little-known option enables specifying sub-functions (although this does not work for nested functions for some unknown reason [bug? oversight?]):</p>
<pre lang='matlab'>
>> str = which('nestedFuncName','in','MFileName');
</pre>
<h3 id="functions">The <i>functions()</i> alternative</h3>
<p>Similar functionality can be achieved via the built-in <i><b>functions</b></i>, using function handles rather than function names:</p>
<pre lang='matlab'>
>> functions(@perfTest)
ans =
    function: 'perfTest'
        type: 'simple'
        file: 'C:\Yair\Books\MATLAB Performance Tuning\Code\perfTest.m'
>> functions(@matfile)
ans =
    function: 'matfile'
        type: 'simple'
        file: 'C:\Program Files\Matlab\R2013b\toolbox\matlab\iofun\matfile.m'
>> fType = functions(@(a)a+1)
fType =
     function: '@(a)a+1'
         type: 'anonymous'
         file: ''
    workspace: {[1x1 struct]}
>> functions(@transpose)
ans =
    function: 'transpose'
        type: 'simple'
        file: ''
</pre>
<p>Unlike <i><b>which</b></i>, <i><b>functions</b></i> can also be used for both sub- <i>and</i> nested-functions:</p>
<pre lang='matlab'>
% The following was called within the confines of a specific m-file function:
K>> fType = functions(@MFileName)
fType =
    function: 'MFileName'
        type: 'simple'
        file: 'C:\Yair\MFileName.m'
K>> fType = functions(@subFunc)
fType =
     function: 'subFunc'
         type: 'scopedfunction'
         file: 'C:\Yair\MFileName.m'
    parentage: {'subFunc'  'MFileName'}
K>> fType = functions(@nestedFunc)
fType =
     function: 'MFileName/nestedFunc'
         type: 'nested'
         file: 'C:\Yair\MFileName.m'
    workspace: {[1x1 struct]}
</pre>
<p>Note that <code>parentage</code> and <code>workspace</code> are undocumented sub-fields of the returned struct: they are mentioned in the official <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/functions.html">doc page</a>, but only in passing, without a format explanation. Also note that <code>workspace</code> is a cell array of a single element (contrary to the official doc &#8211; this is probably an internal bug), containing the actual workspace as a struct (fields = workspace variables). So it should be accessed as <code>fType.workspace{1}.varName</code>. Note that <code>parentage</code> and <code>workspace</code> are present only for certain types of function types.<br />
Have you found any other nifty ways of retrieving function meta-info in run-time? Are you using such meta-info in an interesting manner? If so, please post a short comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/function-definition-meta-info">Function definition meta-info</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/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</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/math-libraries-version-info-upgrade" rel="bookmark" title="Math libraries version info &amp; upgrade">Math libraries version info &amp; upgrade </a> <small>Matlab exposes undocumented info about its internal math libraries; these libraries can be upgraded manually. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/javacomponent" rel="bookmark" title="The javacomponent function">The javacomponent function </a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/function-definition-meta-info/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>treeTable</title>
		<link>https://undocumentedmatlab.com/articles/treetable?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=treetable</link>
					<comments>https://undocumentedmatlab.com/articles/treetable#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Tue, 06 Aug 2013 07:10:20 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[JIDE]]></category>
		<category><![CDATA[uitable]]></category>
		<category><![CDATA[uitree]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4062</guid>

					<description><![CDATA[<p>A description of a sortable, groupable tree-table control that can be used in Matlab is provided. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/treetable">treeTable</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/uitable-cell-colors" rel="bookmark" title="Uitable cell colors">Uitable cell colors </a> <small>A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-line-uitable-column-headers" rel="bookmark" title="Multi-line uitable column headers">Multi-line uitable column headers </a> <small>Matlab uitables can present long column headers in multiple lines, for improved readability. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/checkboxlist" rel="bookmark" title="CheckboxList">CheckboxList </a> <small>Matlab listboxes can be enhanced with checkboxes next to each item. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jide-property-grids" rel="bookmark" title="JIDE Property Grids">JIDE Property Grids </a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Since Matlab 7.0 (R14), Matlab has included a built-in GUI table control (<i><b>uitable</b></i>), at first as a <a target="_blank" href="/articles/legend-semi-documented-feature/#Semi-documented">semi-documented</a> function and in release 7.6 (R2008a) as a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/uitable.html">fully-documented</a> function. Useful as this control is, it lacks many features that are expected in modern GUIs, including sorting, filtering, cell-specific appearance and behavior, gridline customization etc. In <a target="_blank" href="/articles/tag/uitable/">past articles</a> I have explained how <i><b>uitable</b></i> can be customized to achieve a more professional-looking table. I expanded on this in my <a target="_blank" href="/matlab-java-book/">book</a> and my detailed <a target="_blank" href="/articles/uitable-customization-report/"><i><b>uitable</b></i> customization report</a>.<br />
Today I explain how a grouping hierarchy can be achieved in a table control that can be used in Matlab GUI. Such a control, which is a combination of a <a target="_blank" href="/articles/uitree/"><i><b>uitree</b></i></a> and <i><b>uitable</b></i>, is typically called a <i>tree-table</i>. We can find numerous examples of it in everyday usage. I have encapsulated the functionality in a utility called <i><b>treeTable</b></i> on the Matlab File Exchange (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/42946-treetable-create-a-sortable-table-control-with-collapsible-row-groups">#42946</a>). The utility is provided with full source code and open-source license, and readers are welcome to use and modify it. A detailed explanation of the technicalities follows below, but if you&#8217;re just interested in having a sortable, rearrangeable, customizable, groupable table control, then all you need to do is download and use the utility.<br />
<figure style="width: 407px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="treeTable utility" src="https://undocumentedmatlab.com/images/treeTable.jpg" title="treeTable utility" width="407" height="364" /><figcaption class="wp-caption-text">treeTable utility</figcaption></figure></p>
<pre lang='matlab'>
headers = {'ID','Label','Logical1','Logical2','Selector','Numeric'};
data = {1,'M11',true, false,'One', 1011;  ...
        1,'M12',true, true, 'Two', 12;   ...
        1,'M13',false,false,'Many',13.4; ...
        2,'M21',true, false,'One', 21;  ...
        2,'M22',true, true, 'Two', 22;   ...
        3,'M31',true, true, 'Many',31;   ...
        3,'M32',false,true, 'One', -32;  ...
        3,'M33',false,false,'Two', 33; ...
        3,'M34',true, true, 'Many',34;  ...
};
selector = {'One','Two','Many'};
colTypes = {'label','label','char','logical',selector,'double'};
colEditable = {true, true, true, true, true}
icons = {fullfile(matlabroot,'/toolbox/matlab/icons/greenarrowicon.gif'), ...
         fullfile(matlabroot,'/toolbox/matlab/icons/file_open.png'), ...
         fullfile(matlabroot,'/toolbox/matlab/icons/foldericon.gif'), ...
}
% Create the table in the current figure
jtable = treeTable('Container',gcf, 'Headers',headers, 'Data',data, ...
                   'ColumnTypes',colTypes, 'ColumnEditable',colEditable, ...
                   'IconFilenames',icons, 'Groupable',true, 'InteractiveGrouping',false);
% Collapse Row #6, sort descending column #5 (both are 0-based)
jtable.expandRow(5,false);  % 5=row #6; false=collapse
jtable.sortColumn(4,true,false);  % 4=column #5; true=primary; false=descending
</pre>
<p><span id="more-4062"></span></p>
<h3 id="implementation">The basic implementation concept</h3>
<p>Unfortunately, <i><b>uitable</b></i> as-is cannot be customized to have groupable rows. It derives from JIDE&#8217;s <code>SortableTable</code>, rather than one of its groupable derived classes. On the other hand, <i><b>uitree</b></i> (<i>don&#8217;t you agree that after a decade of this so-useful function being semi-documented it ought to be made official?</i>) uses a different class hierarchy outside <code>com.jidesoft.grid</code>, and so it cannot be easily customized to display rows (as opposed to simple labels).<br />
These limitations mean that we cannot use <i><b>uitable</b></i> or <i><b>uitree</b></i> and need to use a custom component. Luckily, such a component is available in all Matlab installations, on all platforms. It is part of the grid components package, on which Matlab GUI has relied for many years, by <a target="_blank" rel="nofollow" href="http://www.jidesoft.com">JIDE Software</a>. JIDE Grids is a collection of components that extend the standard Java Swing <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/table.html">JTable</a> component, and is included in each Matlab installation (<i>/java/jarext/jide/jide-grids.jar</i> under the Matlab root). I discussed <a target="_blank" href="/articles/tag/jide/">multiple JIDE controls</a> in this blog over the years. You can find further details on JIDE Grids in the <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/products/JIDE_Grids_Developer_Guide.pdf">Developer Guide</a> and the <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/">Javadoc documentation</a>.<br />
In fact, there are no less than three different components that we could use in our case: <code>TreeTable</code>, <code>GroupTable</code> and <code>HierarchicalTable</code>:<br />
<center><figure style="width: 417px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="JIDE Grids class hierarchy (we normally use only one of the marked classes)" src="https://undocumentedmatlab.com/images/JIDE_Grids.png" title="JIDE Grids class hierarchy (we normally use only one of the marked classes)" width="417" height="233"/><figcaption class="wp-caption-text">JIDE Grids class hierarchy (we normally use only one of the marked classes)</figcaption></figure></center><br />
Note that we cannot use <code>PropertyTable</code> since that component is limited to only two columns. This is perfect for presenting property names and values, which is the reason it is used by Matlab&#8217;s <i><b>inspect</b></i> function and my generic <a target="_blank" href="/articles/propertiesgui/"><i><b>propertiesGUI</b></i> utility</a> or Levente Hunyadi&#8217;s <a target="_blank" href="/articles/jide-property-grids/">Property Grid utility</a>. But in this case we wish to display a general multi-column table, so <code>PropertyTable</code> is a no-go.<br />
<code>TreeTable</code> and <code>GroupTable</code> enable data rows that have similar type (class), whereas <code>HierarchicalTable</code> enables more flexibility, by allowing display of any component type (including full tables) in child rows. This flexibility comes with a price that customizing a <code>HierarchicalTable</code> is more difficult than <code>TreeTable</code> or <code>GroupTable</code>. These latter two components are quite similar; we use <code>GroupTable</code>, which extends <code>TreeTable</code> with the ability to automatically group rows that have the same value in a certain column.</p>
<h3 id="model">Data model</h3>
<p>The above-mentioned table classes all derive from <code>SortableTable</code> (which also underlies <i><b>uitable</b></i>). Unfortunately, something in the Matlab-Java interface breaks the ability of the JIDE table classes (or rather, their data model) to understand numeric values for what they are. As a result, sorting columns is done lexically, i.e. &#8220;123&#8221; &lt; &#8220;34&#8221; &lt; &#8220;9&#8221;. To fix this, I&#8217;ve included a custom Java table model (<code>MultiClassTableModel</code>) with the <i><b>treeTable</b></i> utility, which automatically infers the column type (class) based on the value in the top row (by overriding the <i>getColumnClass()</i> method).<br />
Using this new class is pretty easy:</p>
<pre lang='matlab'>
% Create the basic data-type-aware model using our data and headers
javaaddpath(fileparts(mfilename('fullpath')));  % add the Java class file to the dynamic java class-path
model = MultiClassTableModel(data, headers);  % data=2D cell or numeric array; headers=cell array of strings
% Wrap the standard model in a JIDE GroupTableModel
com.mathworks.mwswing.MJUtilities.initJIDE;  % initialize JIDE
model = com.jidesoft.grid.DefaultGroupTableModel(model);
model.addGroupColumn(0);  % make the first column the grouping column
model.groupAndRefresh;  % update the model data
% Use the generated model as the data-model of a JIDE GroupTable
jtable = eval('com.jidesoft.grid.GroupTable(model);');  % prevent JIDE alert by run-time (not load-time) evaluation
jtable = handle(javaObjectEDT(jtable), 'CallbackProperties');  % ensure that we're using EDT
% Enable multi-column sorting
jtable.setSortable(true);
% Present the tree-table within a scrollable viewport on-screen
scroll = javaObjectEDT(JScrollPane(jtable));
[jhscroll,hContainer] = javacomponent(scroll, tablePosition, hParent);
set(hContainer,'units', 'normalized','pos',[0,0,1,1]);  % this will resize the table whenever its container is resized
</pre>
<p>Here, <em>com.mathworks.mwswing.MJUtilities.initJIDE</em> is called to initialize JIDE&#8217;s usage within Matlab. Without this call, we may see a JIDE warning message in some Matlab releases. We only need to <em>initJIDE</em> once per Matlab session, although there is no harm in repeated calls.<br />
<i><b>javacomponent</b></i> is the undocumented built-in Matlab function that adds Java Swing components to a Matlab figure, using the given dimensions and parent handle. I discussed it <a target="_blank" href="/articles/javacomponent/">here</a>.</p>
<h3 id="callbacks">Callbacks</h3>
<p>There are two main callbacks that can be used with <i><b>treeTable</b></i>:</p>
<ul>
<li>table data update &#8211; this can be set by uncommenting line #237 of <i>treeTable.m</i>:
<pre lang='matlab'>set(handle(getOriginalModel(jtable),'CallbackProperties'), 'TableChangedCallback', {@tableChangedCallback, jtable});</pre>
<p>which activates the sample <code>tableChangedCallback()</code> function (lines #684-694). Naturally, you can also set your own custom callback function.</p>
<pre lang='matlab'>
% Sample table-editing callback
function tableChangedCallback(hModel,hEvent,jtable)
    % Get the modification data
    modifiedRow = get(hEvent,'FirstRow');
    modifiedCol = get(hEvent,'Column');
    label   = hModel.getValueAt(modifiedRow,1);
    newData = hModel.getValueAt(modifiedRow,modifiedCol);
    % Now do something useful with this info
    fprintf('Modified cell %d,%d (%s) to: %s\n', modifiedRow+1, modifiedCol+1, char(label), num2str(newData));
end  % tableChangedCallback
</pre>
</li>
<li>row selection update &#8211; this is currently enabled in line #238 of <i>treeTable.m</i>:
<pre lang='matlab'>set(handle(jtable.getSelectionModel,'CallbackProperties'), 'ValueChangedCallback', {@selectionCallback, jtable});</pre>
<p>which activates the sample <code>selectionCallback()</code> function (lines #696-705). Naturally, you can also set your own custom callback function.</p>
<pre lang='matlab'>
% Sample table-selection callback
function selectionCallback(hSelectionModel,hEvent,jtable)
    % Get the selection data
    MinSelectionIndex  = get(hSelectionModel,'MinSelectionIndex');
    MaxSelectionIndex  = get(hSelectionModel,'MaxSelectionIndex');
    LeadSelectionIndex = get(hSelectionModel,'LeadSelectionIndex');
    % Now do something useful with this info
    fprintf('Selected rows #%d-%d\n', MinSelectionIndex+1, MaxSelectionIndex+1);
end  % selectionCallback
</pre>
</li>
</ul>
<h3 id="features">Some useful features of <i>treeTable</i></h3>
<p><center><figure style="width: 342px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="treeTable with InteractiveGrouping, multi-column sorting, column rearranging" src="https://undocumentedmatlab.com/images/treeTable_InteractiveGrouping.jpg" title="treeTable with InteractiveGrouping, multi-column sorting, column rearranging" width="342" height="366" /><figcaption class="wp-caption-text">treeTable with interactive grouping, multi-column sorting, column rearranging</figcaption></figure></center></p>
<ul>
<li>Sortable columns (including numeric columns)</li>
<li>Rearrangeable columns (drag headers left/right)</li>
<li>Auto-fit the table columns into the specified container width</li>
<li>Manually resize columns by dragging the column divider gridlines (not just the header dividers as in <i><b>uitable</b></i>)</li>
<li>Flat or groupable table, based on the specified <b>Groupable</b> parameter (default=true)</li>
<li>Ability to interactively group columns (just like Microsoft Outlook) using the <b>InteractiveGrouping</b> parameter (default=false)</li>
<li>Selector cells only show the drop-down arrow of the currently-selected cell (unlike <i><b>uitable</b></i> which shows it for all the column cells)</li>
<li>Selector cells enable editing, unlike <i><b>uitable</b></i> that only enables selecting among pre-defined values</li>
<li>Ability to attach user-defined icons for the leaf rows and the grouping rows (expanded/collapsed)</li>
<li>Easily attach custom cell editors or renderers to any table column (see my <a target="_blank" href="/matlab-java-book/">book</a> and my detailed <a target="_blank" href="/articles/uitable-customization-report/"><i><b>uitable</b></i> customization report</a> for details)</li>
</ul>
<p>All of these features can be turned on/off using the control&#8217;s properties. Again, see my book or report for details (or <a target="_blank" href="/consulting/">ask me</a> to do it for you&#8230;).<br />
I remind readers that I will be visiting clients in Austria (Vienna, Salzburg) and Switzerland (Zurich) in August 18-29. If you live in the area, I will be happy to meet you to discuss how I could bring value to your needs, as consultant, contractor or trainer (<a target="_blank" href="/articles/sparse-data-math-info/#visit">more details</a>).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/treetable">treeTable</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/uitable-cell-colors" rel="bookmark" title="Uitable cell colors">Uitable cell colors </a> <small>A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-line-uitable-column-headers" rel="bookmark" title="Multi-line uitable column headers">Multi-line uitable column headers </a> <small>Matlab uitables can present long column headers in multiple lines, for improved readability. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/checkboxlist" rel="bookmark" title="CheckboxList">CheckboxList </a> <small>Matlab listboxes can be enhanced with checkboxes next to each item. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jide-property-grids" rel="bookmark" title="JIDE Property Grids">JIDE Property Grids </a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/treetable/feed</wfw:commentRss>
			<slash:comments>90</slash:comments>
		
		
			</item>
		<item>
		<title>Math libraries version info &#038; upgrade</title>
		<link>https://undocumentedmatlab.com/articles/math-libraries-version-info-upgrade?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=math-libraries-version-info-upgrade</link>
					<comments>https://undocumentedmatlab.com/articles/math-libraries-version-info-upgrade#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 17 Jul 2013 18:00:36 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3998</guid>

					<description><![CDATA[<p>Matlab exposes undocumented info about its internal math libraries; these libraries can be upgraded manually. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/math-libraries-version-info-upgrade">Math libraries version info &amp; upgrade</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/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/function-definition-meta-info" rel="bookmark" title="Function definition meta-info">Function definition meta-info </a> <small>There are multiple ways to retrieve meta-info about functions in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-infiniband-with-matlab-parallel-computing-toolbox" rel="bookmark" title="Using Infiniband with Matlab Parallel Computing Toolbox">Using Infiniband with Matlab Parallel Computing Toolbox </a> <small>Infiniband networking can significantly improve PCT performance in Matlab parallelization and distributed computing. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/ip-address-input-control" rel="bookmark" title="IP address input control">IP address input control </a> <small>A built-in JIDE control can be used in Matlab GUI for IP-address entry/display. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i><b>version</b></i> is a well-known Matlab function, which displays and returns information about the installed release:</p>
<pre lang='matlab'>
>> [v,d] = version
v =
8.1.0.604 (R2013a)
d =
February 15, 2013
>> version('-java')
ans =
Java 1.6.0_17-b04 with Sun Microsystems Inc. Java HotSpot(TM) 64-Bit Server VM mixed mode
</pre>
<p>This is pretty boring stuff. But it starts to get interesting when we learn the undocumented fact that <i><b>version</b></i> can also report version information of the installed math libraries, starting in R2009b (Matlab 7.9):<br />
<span class="alignright"><img loading="lazy" decoding="async" alt="FFTW logo" src="https://undocumentedmatlab.com/images/fftw-logo-med.png" title="FFTW logo" width="165" height="54" /><br /><img loading="lazy" decoding="async" alt="LAPACK logo" src="https://undocumentedmatlab.com/images/Lapack-logo.png" title="LAPACK logo" width="165" height="140" /></span></p>
<pre lang='matlab'>
% R2013a (Matlab 8.1) on Win7 64b
>> version('-fftw')
ans =
FFTW-3.3.1-sse2-avx
>> version('-blas')
ans =
Intel(R) Math Kernel Library Version 10.3.11 Product Build 20120606 for Intel(R) 64 architecture applications
>> version('-lapack')
ans =
Intel(R) Math Kernel Library Version 10.3.11 Product Build 20120606 for Intel(R) 64 architecture applications
Linear Algebra PACKage Version 3.4.1
</pre>
<p>This information is sometimes useful, and is <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/327906">sometimes asked</a> by users. Specific versions of <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms">BLAS</a>, <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/LAPACK">LAPACK</a> and <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/FFTW">FFTW</a>, which Matlab uses under its hood for all linear algebra and FFW computations, may exhibit idiosyncrasies that may be important in certain cases.<br />
<span id="more-3998"></span><br />
In versions up to R2013a, this information could also be retrieved using the <i><b>internal.matlab.language.versionPlugins.*</b></i> mex functions (e.g., <i><b>internal.matlab.language.versionPlugins.blas</b></i>, which runs the mex function <i>%matlabroot%\toolbox\matlab\matfun\+internal\+matlab\+language\+versionPlugins\blas.mexw64</i>). I&#8217;ll have a separate post (or series of posts) on Matlab&#8217;s internal.* functions, but at least with regards to version information they should NOT be relied upon. These interfaces (and their mex files) have changed their name and availability in some Matlab releases. Luckily, the <i><b>version</b></i> format that I showed above seems pretty stable and can be used as-is across multiple Matlab releases.<br />
Here is a summary of the math libraries version in recent Matlab releases (Windows only):</p>
<table border="0">
<thead>
<tr>
<th>Matlab release</th>
<th>FFTW</th>
<th>MKL (BLAS)</th>
<th>LAPACK</th>
</tr>
</thead>
<tr>
<td>R2009b SP1 (7.9.1)</td>
<td>3.2.0-sse2</td>
<td>10.2.2 (2009-08-14)</td>
<td>3.1.1</td>
</tr>
<tr>
<td>R2010a (7.10)</td>
<td>3.2.2-sse2</td>
<td>10.2.2 (2009-08-14)</td>
<td>3.2.1</td>
</tr>
<tr>
<td>R2010b (7.11)</td>
<td>3.2.2-sse2</td>
<td>10.2.3 (2009-11-30)</td>
<td>3.2.1</td>
</tr>
<tr>
<td>R2011a (7.12)</td>
<td>3.2.2-sse2</td>
<td>10.2.6 (2010-07-28)</td>
<td>3.2.2</td>
</tr>
<tr>
<td>R2011b (7.13)</td>
<td>3.2.2-sse2</td>
<td>10.3.2 (2011-01-17)</td>
<td>3.2.2</td>
</tr>
<tr>
<td>R2012a (7.14)</td>
<td>3.2.2-sse2</td>
<td>10.3.5 (2011-07-20)</td>
<td>3.3.1</td>
</tr>
<tr>
<td>R2012b (8.0)</td>
<td>3.3.1-sse2</td>
<td>10.3.9 (2012-01-31)</td>
<td>3.3.1</td>
</tr>
<tr>
<td>R2013a (8.1)</td>
<td>3.3.1-sse2-avx</td>
<td>10.3.11 (2012-06-06)</td>
<td>3.4.1</td>
</tr>
</table>
<p>Note that the LAPACK version is not always updated together with BLAS, although they are both part of Intel&#8217;s MKL (more on MKL below).<br />
<b><u>Addendum 2013-10-9</u></b>: The undocumented <code>-modules</code> option of the <i><b>version</b></i> command provides the list of currently installed libraries:</p>
<pre lang='matlab'>
>> version -modules
C:\Program Files\Matlab\R2013b\bin\win64\libut.dll Version < unknown >
C:\Program Files\Matlab\R2013b\bin\win64\libmwfl.dll Version < unknown >
C:\Program Files\Matlab\R2013b\bin\win64\libmx.dll Version 8.2.0.627
C:\Program Files\Matlab\R2013b\bin\win64\zlib1.dll Version < unknown >
...
</pre>
<p>[/Addendum]<br />
Do you know of any other hidden version info anywhere in Matlab? If so, please post a comment below.</p>
<h3 id="Upgrading">Upgrading library versions</h3>
<p>It may well be possible for users to upgrade the internal libraries that Matlab uses to the latest version, assuming that backward compatibility is preserved in these libraries (which I suppose is the case). Naturally, you can only upgrade if you have a license for the upgraded library. For those interested, the libraries are located in <i>%matlabroot%/bin/%arch%</i>. For example: <i>C:\Program Files\Matlab\R2013b\bin\win64\mkl.dll</i> is Intel&#8217;s <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Math_Kernel_Library">MKL</a> (Math Kernel Library), which contains BLAS and LAPACK. Using this example, the <a target="_blank" rel="nofollow" href="http://software.intel.com/en-us/intel-mkl/">latest official version</a> of MKL is 11.0, which <a target="_blank" rel="nofollow" href="http://software.intel.com/en-us/articles/intel-mkl-110-release-notes">promises</a> several important improvements over R2013a&#8217;s bundled version (10.3.11):</p>
<ul>
<li>A <a target="_blank" rel="nofollow" href="http://software.intel.com/en-us/articles/svd-multithreading-bug-in-mkl">fix for a bug</a> in the <i><b>svd</b></i> routines</li>
<li>Improved performance</li>
<li>Improved support for Intel&#8217;s <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Advanced_Vector_Extensions">AVX2</a> instruction set (see related <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/328084#901644">comment</a> by Eric Sampson recently)</li>
<li>Improved functionality of MKL&#8217;s FFT implementation &#8212; Matlab&#8217;s <i><b>*fft</b></i> functions use FFTW, but <a target="_blank" rel="nofollow" href="http://www.fftw.org/speed/">in some cases</a> MKL&#8217;s FFT implementation outperforms FFTW&#8217;s. You may wish to use MKL&#8217;s <a target="_blank" rel="nofollow" href="http://software.intel.com/sites/products/documentation/hpc/mkl/mklman/GUID-A23603DA-B6D1-48AA-90D2-A415302F27D9.htm">FFTW wrapper</a> in such cases rather than calling MKL&#8217;s FFT routines directly.</li>
</ul>
<p>Similarly, FFTW&#8217;s latest stable release is 3.3.3, <a target="_blank" rel="nofollow" href="http://www.fftw.org/release-notes.html">offers advantages</a> compared to R2013a&#8217;s bundled 3.3.1 version. Unfortunately, unlike MKL, FFTW is not bundled as a replaceable library file. I believe that FFTW is directly integrated in Matlab&#8217;s code. However, nothing prevents us from <a target="_blank" rel="nofollow" href="http://www.fftw.org/download.html">downloading</a> the latest library and using it directly.<br />
<span class="alignleft"><img loading="lazy" decoding="async" alt="Warning!" src="https://undocumentedmatlab.com/images/warning.gif" title="Warning!" width="48" height="48" /></span> Needless to say, upgrading specific DLLs in Matlab can be extremely dangerous, and is entirely unsupported by MathWorks. Don&#8217;t come crying if Matlab starts to crash, or even worse &#8211; to return incorrect numerical results. If you design a car with upgraded libs, just let me know please, so that I&#8217;d know not to buy that model&#8230; I don&#8217;t often place such warnings on this blog. After all, this is a blog about undocumented / unsupported stuff. So when I do explicitly warn like this, you should take extra note. Upgrading Matlab&#8217;s math libs is purely an exercise for adventurous engineers who like to blow things up (oh, the sheer pleasure of charting undocumented waters!).<br />
<b><u>Addendum 2013-10-9</u></b>: Amro&#8217;s <a href="/articles/math-libraries-version-info-upgrade/#comment-226776">comment</a> below provides links to several articles that show how we can redirect Matlab to use a different BLAS/LAPACK library than the default (in MKL/ACML), by either setting the <code>BLAS_VERSION</code> environment variable or by updating the <i>blas.spec</i> and <i>lapack.spec</i> files in the libs folder. One user has <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/129077">reported</a> that in his specific case this achieved a 30% speedup with no change to the code. Note that both of these options only apply to MKL/ACML, and not to other libraries &#8211; in those cases, AFAIK, only a direct replacement of the physical file will work. [/Addendum]</p>
<h3 id="IPP">IPP library</h3>
<p>If you have the Image Processing Toolbox (IPT), then you will also find Intel&#8217;s <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Integrated_Performance_Primitives">IPP</a> (Integrated Performance Primitives) library (<i>ippl.dll</i>) in the same folder as <i>mkl.dll</i>. IPP is used by IPT for running some highly-optimized image-processing functions.<br />
<span class="alignright"><img loading="lazy" decoding="async" alt="Intel logo" src="https://undocumentedmatlab.com/images/Intel-logo.png" title="Intel logo" width="200" height="132" /></span> Unfortunately, I could not find a parameter of <i><b>version</b></i> that returns the IPP version used by Matlab. However, we can get IPP&#8217;s version info using the <i><b>ippl</b></i> function, which is a semi-documented function in IPT (i.e., it has detailed help, but for some reason not an official doc page):</p>
<pre lang='matlab'>
% R2013a (Matlab 8.1) on Win7 64b
>> [isIpplEnabled, ipplVersion] = ippl
isIpplEnabled =
     1                     % == true
ipplVersion =
    'ippie9_t.lib 7.0 build 205.58 7.0.205.1054 e9   Apr 18 2011'
</pre>
<p>A few IPP-related aspects that you might find interesting in this regard:</p>
<ul>
<li>Matlab currently (R2013a) uses IPPL 7.0 dated April 2011 &#8211; the <a target="_blank" rel="nofollow" href="http://software.intel.com/en-us/intel-ipp">latest version</a> is 8.0 dated June 26, 2013 (only 3 weeks ago) <a target="_blank" rel="nofollow" href="http://software.intel.com/en-us/articles/intel-ipp-80-library-release-notes">includes</a> significant performance boosts. Note that between 7.0 and 8.0 there was a 7.1 release that <a target="_blank" rel="nofollow" href="http://software.intel.com/en-us/articles/intel-ipp-71-library-whats-new">also had</a> significant improvements, especially for modern CPUs. The 8.0 release changed some function names, so for compatibility with Matlab you might discover that you need to settle for the 7.1 DLL. This could still bring significant benefits.</li>
<li>Matlab currently limits IPP usage to uints, floats and (since R2012b) doubles, although (AFAIK) IPP also supports signed ints. For signed ints Matlab reverts to much slower functional processing, which seems a pity. I&#8217;m not 100% certain that these are indeed supported by IPP for the specific cases in which Matlab currently blocks them, but I think it&#8217;s worth a check &#8211; the performance boost could be worth the effort.</li>
<li>Matlab currently uses IPP only for some of the image-processing functions. It would make sense to use IPP much more widely, e.g. math, stats, convolution, FFT/FIR (I&#8217;m not sure it&#8217;s faster than FFTW, but it may be worth a check) and many others &#8211; IPP is much more versatile than an image processing toolkit (<a target="_blank" rel="nofollow" href="http://software.intel.com/en-us/intel-ipp">read here</a>).</li>
</ul>
<p>Even if we don&#8217;t upgrade the <i>ippl.dll</i> or <i>mkl.dll</i> version, we may still benefit by accessing them directly in Matlab and/or MEX code. They can be used in Matlab just like any other DLL. There are plenty of online resources that can help us program using the IPP/MKL functionalities, even on the <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/search_results?dur=all&#038;search_string=tag%3Amkl">Matlab CSSM newsgroup</a>. It seems that quite a few Matlab users try to work directly with these libraries, sometimes perhaps not realizing that they are already pre-bundled within Matlab.<br />
If you have successfully used one of these libraries directly in Matlab, and/or successfully upgraded the libs for some use, please share your experience by posting a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/math-libraries-version-info-upgrade">Math libraries version info &amp; upgrade</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/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/function-definition-meta-info" rel="bookmark" title="Function definition meta-info">Function definition meta-info </a> <small>There are multiple ways to retrieve meta-info about functions in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-infiniband-with-matlab-parallel-computing-toolbox" rel="bookmark" title="Using Infiniband with Matlab Parallel Computing Toolbox">Using Infiniband with Matlab Parallel Computing Toolbox </a> <small>Infiniband networking can significantly improve PCT performance in Matlab parallelization and distributed computing. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/ip-address-input-control" rel="bookmark" title="IP address input control">IP address input control </a> <small>A built-in JIDE control can be used in Matlab GUI for IP-address entry/display. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/math-libraries-version-info-upgrade/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Handle Graphics Behavior</title>
		<link>https://undocumentedmatlab.com/articles/handle-graphics-behavior?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=handle-graphics-behavior</link>
					<comments>https://undocumentedmatlab.com/articles/handle-graphics-behavior#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 06 Mar 2013 18:00:19 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3665</guid>

					<description><![CDATA[<p>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handle-graphics-behavior">Handle Graphics Behavior</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-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</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/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/copyobj-behavior-change-in-hg2" rel="bookmark" title="copyobj behavior change in HG2">copyobj behavior change in HG2 </a> <small>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab&#8217;s Handle Graphics (HG) have been around for ages. Still, to this day it contains many hidden gems. Today I discuss HG&#8217;s <b>Behavior</b> property, which is a standard <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties/">undocumented hidden property</a> of all HG objects.<br />
<b>Behavior</b> is not normally updated directly (although there is absolutely nothing to prevent this), but rather via the <a target="_blank" href="/articles/legend-semi-documented-feature/#Semi-documented">semi-documented</a> built-in accessor functions <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i>. This manner of accessing <b>Behavior</b> is similar to its undocumented sibling property <b>ApplicationData</b>, which is accessed by the corresponding <i><b>getappdata</b></i> and <i><b>setappdata</b></i> functions.</p>
<h3 id="usage">Using HB behaviors</h3>
<p><i><b>hggetbehavior</b></i> with no input args displays a list of all pre-installed HG behaviors:</p>
<pre lang='matlab'>
>> hggetbehavior
   Behavior Object Name         Target Handle
   --------------------------------------------
   'Plotedit'...................Any Graphics Object
   'Print'......................Any Graphics Object
   'Zoom'.......................Axes
   'Pan'........................Axes
   'Rotate3d'...................Axes
   'DataCursor'.................Axes and Axes Children
   'MCodeGeneration'............Axes and Axes Children
   'DataDescriptor'.............Axes and Axes Children
   'PlotTools'..................Any graphics object
   'Linked'.....................Any graphics object
   'Brush'......................Any graphics object
</pre>
<p><span id="more-3665"></span><br />
<i><b>hggetbehavior</b></i> can be passed a specific behavior name (or cell array of names), in which case it returns the relevant behavior object handle(s):</p>
<pre lang='matlab'>
>> hBehavior = hggetbehavior(gca, 'Zoom')
hBehavior =
	graphics.zoombehavior
>> hBehavior = hggetbehavior(gca, {'Zoom', 'Pan'})
hBehavior =
	handle: 1-by-2
</pre>
<p>As the name indicates, the behavior object handle controls the behavior of the relevant action. For example, the behavior object for Zoom contains the following properties:</p>
<pre lang='matlab'>
>> hBehavior = hggetbehavior(gca, 'Zoom');
>> get(hBehavior)
       Enable: 1        % settable: true/false
    Serialize: 1        % settable: true/false
         Name: 'Zoom'   % read-only
        Style: 'both'   % settable: 'horizontal', 'vertical' or 'both'
</pre>
<p>By setting the behavior&#8217;s properties, we can control whether the axes will have horizontal, vertical, 2D or no zooming enabled, regardless of whether or not the toolbar/menu-bar zoom item is selected:</p>
<pre lang='matlab'>
hBehavior.Enable = false;         % or: set(hBehavior,'Enable',false)
hBehavior.Style  = 'horizontal';  % or: set(hBehavior,'Style','horizontal')
</pre>
<p>This mechanism is used internally by Matlab to disable zoom/pan/rotate3d (see <i>%matlabroot%/toolbox/matlab/graphics/@graphics/@zoom/setAllowAxesZoom.m</i> and similarly <i>setAllowAxesPan, setAllowAxesRotate</i>).<br />
At this point, some readers may jump saying that we can already do this via the zoom object handle that is returned by the <i><b>zoom</b></i> function (where the <b>Style</b> property was renamed <b>Motion</b>, but never mind). However, I am just trying to show the general usage. Not all behaviors have similar documented customizable mechanisms. In fact, using behaviors we can control specific behaviors for separate HG handles in the same figure/axes.<br />
For example, we can set a different callback function to different HG handles for displaying a plot data-tip (a.k.a. data cursor). I have explained in the past how to <a target="_blank" href="/articles/controlling-plot-data-tips/">programmatically control data-tips</a>, but doing so relies on the figure <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/datacursormode.html"><i><b>datacursormode</b></i></a>, which is figure-wide. If we want to display different data-tips for different plot handles, we would need to add logic into our custom update function that would change the returned string based on the clicked handle. Using HG behavior we can achieve the same goal much easier:</p>
<pre lang='matlab'>
% Use dataCursorLineFcn() for the line data-tip
bh = hggetbehavior(hLine,'DataCursor');
set(bh,'UpdateFcn',@dataCursorLineFcn);
% Use dataCursorAnnotationFcn() for the annotation data-tip
bh = hggetbehavior(hAnnotation,'DataCursor');
set(bh,'UpdateFcn',{@dataCursorAnnotationFcn,extraData});
</pre>
<p>Note: there is also the related semi-documented function <i><b>hgbehaviorfactory</b></i>, which is used internally by <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i>. I do not see any need for using <i><b>hgbehaviorfactory</b></i> directly, only <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i>.</p>
<h3 id="custom">Custom behaviors</h3>
<p>The standard behavior objects are UDD schema objects (i.e., the old object-oriented mechanism in MATLAB). They are generally located in a separate folder beneath <i>%matlabroot%/toolbox/matlab/graphics/@graphics/</i>. For example, the Zoom behavior object is located in <i>%matlabroot%/toolbox/matlab/graphics/@graphics/@zoombehavior/</i>. These behavior object folders generally contain a <i>schema.m</i> file (that defines the behavior object class and its properties), and a <i>dosupport.m</i> function that returns a logical flag indicating whether or not the behavior is supported for the specified handle. These are pretty standard functions, here is an example:</p>
<pre lang='matlab'>
% Zoom behavior's schema.m:
function schema
% Copyright 2003-2006 The MathWorks, Inc.
pk = findpackage('graphics');
cls = schema.class(pk,'zoombehavior');
p = schema.prop(cls,'Enable','bool');
p.FactoryValue = true;
p = schema.prop(cls,'Serialize','MATLAB array');
p.FactoryValue = true;
p.AccessFlags.Serialize = 'off';
p = schema.prop(cls,'Name','string');
p.AccessFlags.PublicSet = 'off';
p.AccessFlags.PublicGet = 'on';
p.FactoryValue = 'Zoom';
p.AccessFlags.Serialize = 'off';
% Enumeration Style Type
if (isempty(findtype('StyleChoice')))
    schema.EnumType('StyleChoice',{'horizontal','vertical','both'});
end
p = schema.prop(cls,'Style','StyleChoice');
p.FactoryValue = 'both';
</pre>
<pre lang='matlab'>
% Zoom behavior's dosupport.m:
function [ret] = dosupport(~,hTarget)
% Copyright 2003-2009 The MathWorks, Inc.
% axes
ret = ishghandle(hTarget,'axes');
</pre>
<p>All behaviors must define the <b>Name</b> property, and most behaviors also define the <b>Serialize</b> and <b>Enable</b> properties. In addition, different behaviors define other properties. For example, the DataCursor behavior defines the <b>CreateNewDatatip</b> flag and no less than 7 callbacks:</p>
<pre lang='matlab'>
function schema
% Copyright 2003-2008 The MathWorks, Inc.
pk = findpackage('graphics');
cls = schema.class(pk,'datacursorbehavior');
p = schema.prop(cls,'Name','string');
p.AccessFlags.PublicSet = 'off';
p.AccessFlags.PublicGet = 'on';
p.FactoryValue = 'DataCursor';
schema.prop(cls,'StartDragFcn','MATLAB callback');
schema.prop(cls,'EndDragFcn','MATLAB callback');
schema.prop(cls,'UpdateFcn','MATLAB callback');
schema.prop(cls,'CreateFcn','MATLAB callback');
schema.prop(cls,'StartCreateFcn','MATLAB callback');
schema.prop(cls,'UpdateDataCursorFcn','MATLAB callback');
schema.prop(cls,'MoveDataCursorFcn','MATLAB callback');
p = schema.prop(cls,'CreateNewDatatip','bool');
p.FactoryValue = false;
p.Description = 'True will create a new datatip for every mouse click';
p = schema.prop(cls,'Enable','bool');
p.FactoryValue = true;
p = schema.prop(cls,'Serialize','MATLAB array');
p.FactoryValue = true;
p.AccessFlags.Serialize = 'off';
</pre>
<p>Why am I telling you all this? Because in addition to the standard behavior objects we can also specify custom behaviors to HG handles. All we need to do is mimic one of the standard behavior object classes in a user-defined class, and then use <i><b>hgaddbehavior</b></i> to add the behavior to an HG handle. Behaviors are differentiated by their <b>Name</b> property, so we can either use a new name for the new behavior, or override a standard behavior by reusing its name.</p>
<pre lang='matlab'>hgaddbehavior(hLine,myNewBehaviorObject)</pre>
<p>If you wish the behavior to be serialized (saved) to disk when saving the figure, you should add the <b>Serialize</b> property to the class and set it to <code>true</code>, then use <i><b>hgaddbehavior</b></i> to add the behavior to the relevant HG handle. The <b>Serialize</b> property is searched-for by the <i><b>hgsaveStructDbl</b></i> function when saving figures (I described <i><b>hgsaveStructDbl</b></i> <a target="_blank" href="/articles/handle2struct-struct2handle-and-matlab-8/">here</a>). All the standard behaviors except DataDescriptor have the <b>Serialize</b> property (I don&#8217;t know why DataDescriptor doesn&#8217;t).<br />
Just for the record, you can also use MCOS (not just UDD) class objects for the custom behavior, as mentioned by the internal comment within the <i><b>hgbehaviorfactory</b></i> function. Most standard behaviors use UDD schema classes; an example of an MCOS behavior is PlotEdit that is found at <i>%matlabroot%/toolbox/matlab/graphics/+graphics/+internal/@PlotEditBehavor/PlotEditBehavor.m</i>.</p>
<h3 id="ishghandle"><i>ishghandle</i>&#8216;s undocumented type input arg</h3>
<p>Note that the Zoom behavior&#8217;s <i>dosupport</i> function uses an undocumented format of the built-in <i><b>ishghandle</b></i> function, namely accepting a second parameter that specifies a specific handle type, which presumably needs to correspond to the handle&#8217;s <b>Type</b> property:</p>
<pre lang='matlab'>ret = ishghandle(hTarget,'axes');</pre>
<h3 id="hasbehavior">The <i>hasbehavior</i> function</h3>
<p>Another semi-documented built-in function called <i><b>hasbehavior</b></i> is located right next to <i><b>hggetbehavior</b></i> and <i><b>hgaddbehavior</b></i> in the <i>%matlabroot%/toolbox/matlab/graphics/</i> folder.<br />
Despite its name, and the internal comments that specifically mention HG behaviors, this function is entirely independent of the HG behavior mechanism described above, and in fact makes use of the <b>ApplicationData</b> property rather than <b>Behavior</b>. I have no idea why this is so. It may be a design oversight or some half-baked attempt by a Mathworker apprentice to emulate the behavior mechanism. Even the function name is misleading: in fact, <i><b>hasbehavior</b></i> not only checks whether a handle has some &#8220;behavior&#8221; (in the 2-input args format) but also sets this flag (in the 3-input args format).<br />
<i><b>hasbehavior</b></i> is used internally by the legend mechanism, to determine whether or not an HG object (line, scatter group, patch, annotation etc.) should be added to the legend. This can be very important for <a target="_blank" href="/articles/plot-performance/#Legend">plot performance</a>, since the legend would not need to be updated whenever these objects are modified in some manner:</p>
<pre lang='matlab'>
hLines = plot(rand(3,3));
hasbehavior(hLines(1), 'legend', false);   % line will not be in legend
hasbehavior(hLines(2), 'legend', true);    % line will be in legend
</pre>
<p>(for anyone interested, the relevant code that checks this flag is located in <i>%matlabroot%/toolbox/matlab/scribe/private/islegendable.m</i>)<br />
<i><b>hasbehavior</b></i> works by using a dedicated field in the handle&#8217;s <b>ApplicationData</b> struct with a logical flag value (<code>true/false</code>). The relevant field is called <code>[name,'_hgbehavior']</code>, where <code>name</code> is the name of the so-called &#8220;behavior&#8221;. In the example above, it creates a field called &#8220;legend_hgbehavior&#8221;.<br />
Do you know of any neat uses for HG behaviors? If so, please post a comment <a href="/articles/handle-graphics-behavior/#respond">below</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handle-graphics-behavior">Handle Graphics Behavior</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-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</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/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/copyobj-behavior-change-in-hg2" rel="bookmark" title="copyobj behavior change in HG2">copyobj behavior change in HG2 </a> <small>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/handle-graphics-behavior/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing menu items part 1</title>
		<link>https://undocumentedmatlab.com/articles/customizing-menu-items-part-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-menu-items-part-1</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-menu-items-part-1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 25 Apr 2012 18:14:08 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Menubar]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2897</guid>

					<description><![CDATA[<p>Matlab menus can be customized in a variety of undocumented manners - first article of a series. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1">Customizing menu items part 1</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-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uitree-nodes" rel="bookmark" title="Customizing uitree nodes &#8211; part 1">Customizing uitree nodes &#8211; part 1 </a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Over the past years, I have not posted articles dealing with menu items. I have shown how to <a target="_blank" href="/articles/modifying-default-toolbar-menubar-actions/">directly access menu items&#8217; hidden handles</a>, but not much more than that. A year ago I <a target="_blank" href="/articles/2010-perspective/">promised</a> a mini-series on menu customizations, and it&#8217;s time to keep my promise. In today&#8217;s article, the first in the mini-series, I will present several undocumented menu customization topics that rely on pure-Matlab (i.e, no Java today). The next article in this series will focus on Java-based customizations.</p>
<h3 id="Invoking">Invoking menu item callbacks</h3>
<p>As noted above, a figure window&#8217;s menu items can be directly accessed. Once we access a menu item&#8217;s handle, we can extract its <b>Callback</b> property and directly invoke it (for example, using the semi-documented <a target="_blank" href="/articles/hgfeval/"><i><b>hgfeval</b></i> function</a>). Note that menu callbacks are kept in <b>Callback</b>, while toolbar callbacks are kept in <b>ClickedCallback</b>.<br />
Menu callbacks generally use internal <a target="_blank" href="/articles/legend-semi-documented-feature/#Semi-documented">semi-documented</a> functions (i.e., having a readable help section but no doc, online help, or official support), which are part of Matlab&#8217;s uitools folder. These functions are specific to each top-level menu tree: <i><b>filemenufcn, editmenufcn, viewmenufcn, insertmenufcn, toolsmenufcn, desktopmenufcn, winmenu</b></i>, and <i><b>helpmenufcn</b></i> implement the figure&#8217;s eight respective top-level menu trees&#8217; callbacks. These functions accept an optional figure handle (otherwise, <i><b>gcbf</b></i> is assumed), followed by a string specifying the specific menu item whose action needs to be run. <i><b>webmenufcn</b></i> implements the Help menu&#8217;s Web Resources sub-menu callbacks in a similar manner.<br />
Use of these functions makes it easy to invoke a menu action directly from our Matlab code: instead of accessing the relevant menu item and invoking its <b>Callback</b>, we simply find out the menu item string in advance and use it directly. For example,</p>
<pre lang='matlab'>
filemenufcn FileClose;
editmenufcn(hFig,'EditPaste');
</pre>
<p><i><b>uimenufcn</b></i> is a related fully-undocumented (built-in) function, available since Matlab R11 (late 1990s). It accepts a figure handle (or the zero [0] handle to indicate the desktop) and action name. For example, the fully-documented <i><b>commandwindow</b></i> function uses the following code to bring the Command Window into focus:</p>
<pre lang='matlab'>uimenufcn(0, 'WindowCommandWindow');</pre>
<h3 id="Uitools">Customizing menus via uitools</h3>
<p><i><b>makemenu</b></i> is another semi-documented uitool function that enables easy creation of hierarchical menu trees with separators and accelerators. It is a simple and effective wrapper for <i><b>uimenu</b></i>. <i><b>makemenu</b></i> is a useful function that has been made obsolete (grandfathered) without any known replacement.<br />
<i><b>makemenu</b></i> accepts four parameters: a figure handle, a char matrix of labels (&#8216;&gt;&#8217; indicating sub item, &#8216;&gt;&gt;&#8217; indicating sub-sub items etc.; &#8216;&amp;&#8217; indicating keyboard shortcut; &#8216;^x&#8217; indicating an accelerator key; &#8216;-&#8216; indicating a separator line), a char matrix of callbacks, and an optional char matrix of tags (empty by default). <i><b>makemenu</b></i> makes use of another semi-documented grandfathered function, <i><b>menulabel</b></i>, to parse the specified label components. <i><b>makemenu</b></i> returns an array of handles of the created <i><b>uimenu</b></i> items:</p>
<pre lang='matlab'>
labels = str2mat('&File', ...    % File top menu
           '>&New^n', ...           % File=>New
           '>&Open', ...            % File=>Open
           '>>Open &document^d', ...    % File=>Open=>doc
           '>>Open &graph^g', ...       % File=>Open=>graph
           '>-------', ...          % File=>separator line
           '>&Save^s', ...          % File=>Save
           '&Edit', ...		% Edit top menu
           '&View', ...		% View top menu
           '>&Axis^a', ...          % View=>Axis
           '>&Selection region^r'); % View=>Selection
calls = str2mat('', ...		% no action: File top menu
           'disp(''New'')', ...
           '', ...			% no action: Open sub-menu
           'disp(''Open doc'')', ...
           'disp(''Open graph'')', ...
           '', ...			% no action: Separator
           'disp(''Save'')', ...
           '', ...			% no action: Edit top menu
           '', ...			% no action: View top menu
           'disp(''View axis'')', ...
           'disp(''View selection region'')');
handles = makemenu(hFig, labels, calls);
set(hFig,'menuBar','none');
</pre>
<p><center><figure style="width: 267px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="A simple figure menu" src="https://undocumentedmatlab.com/images/makemenu.png" title="A simple figure menu" width="267" height="148"/><figcaption class="wp-caption-text">A simple figure menu</figcaption></figure></center></p>
<h3 id="HTML">Customizing menus via HTML</h3>
<p>Since menu items share the same <a target="_blank" href="/articles/html-support-in-matlab-uicomponents/">HTML/CSS support feature</a> as all Java Swing labels, we can specify font size/face/color, bold, italic, underline, superscript/subscript, and practically any HTML formatting.<br />
Note that some features, such as the font or foreground/background colors, have specific properties that we can set using the Java handle, instead of using HTML. The benefit of using HTML is that it enables setting all the formatting in a single property. HTML does not require using Java – just pure Matlab (see the following example).<br />
Multi-line menu items can easily be done with HTML: simply include a <code>&lt;br&gt;</code> element in the label – the menu item will split into two lines and automatically resize vertically when displayed:</p>
<pre lang='matlab'>
txt1 = '<html><b><u><i>Save</i></u>';
txt2 = '<font color="red"><sup>this file</sup></font></b></html>';
txt3 = '<br />this file as...';
set(findall(hFig,'tag','figMenuFileSave'),   'Label',[txt1,txt2]);
set(findall(hFig,'tag','figMenuFileSaveAs'), 'Label',[txt1,txt3]);
</pre>
<p><center><figure style="width: 185px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="A multi-line HTML-rendered menu item" src="https://undocumentedmatlab.com/images/uimenu2.png" title="A multi-line HTML-rendered menu item" width="185" height="184"/><figcaption class="wp-caption-text">A multi-line HTML-rendered menu item</figcaption></figure></center></p>
<pre lang='matlab'>
set(hMenuItem, 'Label',['<html>&2: C:\My Documents\doc.txt<br />'
   '<font size="-1" face="Courier New" color="red">&nbsp;&nbsp; '
   'Date: 15-Jun-2011 13:23:45<br />&nbsp;&nbsp; Size: 123 KB</font></html>']);
</pre>
<p><center><figure style="width: 411px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="HTML-rendered menu items" src="https://undocumentedmatlab.com/images/uimenu2b.png" title="HTML-rendered menu items" width="411" height="246"/><figcaption class="wp-caption-text">HTML-rendered menu items</figcaption></figure></center><br />
Much more complex customizations can be achieved using Java. So stay tuned to part 2 of this mini-series&#8230;<br />
Note: Menu customization is explored in depth in section 4.6 of my <a target="_blank" href="/matlab-java-book/">book</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1">Customizing menu items part 1</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-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uitree-nodes" rel="bookmark" title="Customizing uitree nodes &#8211; part 1">Customizing uitree nodes &#8211; part 1 </a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-menu-items-part-1/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
	</channel>
</rss>
