<?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>COM &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/com/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 23 Jan 2013 18:00:09 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.3</generator>
	<item>
		<title>uiinspect</title>
		<link>https://undocumentedmatlab.com/articles/uiinspect?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=uiinspect</link>
					<comments>https://undocumentedmatlab.com/articles/uiinspect#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 23 Jan 2013 18:00:09 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Dot-Net]]></category>
		<category><![CDATA[JIDE]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[UIInspect]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3477</guid>

					<description><![CDATA[<p>uiinspect is a Matlab utility that displays detailed information about an object's methods, properties and callbacks in a single GUI window.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uiinspect">uiinspect</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/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>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-gui-display-container-hierarchy" rel="bookmark" title="FindJObj GUI &#8211; display container hierarchy">FindJObj GUI &#8211; display container hierarchy </a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/propertiesgui" rel="bookmark" title="propertiesGUI">propertiesGUI </a> <small>propertiesGUI is a utility that presents property-value structs in a convenient table format, useful in Matlab GUIs. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>After several years in which I have mentioned my <i><b>uiinspect</b></i> utility in posts, I figured it is high time to actually describe this utility in detail.<br />
<figure style="width: 500px" class="wp-caption alignright"><img fetchpriority="high" decoding="async" alt="uiinspect in action (Java, HG, COM)" src="https://undocumentedmatlab.com/images/uiinspect.gif" title="uiinspect in action (Java, HG, COM)" width="500" height="387"/><figcaption class="wp-caption-text">uiinspect in action (Java, HG, COM)</figcaption></figure><br />
<i><b>uiinspect</b></i>, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect">downloadable</a> from the Matlab file Exchange, is a Matlab GUI utility that inspects the specified object and provides detailed information about its super-classes, methods, properties, static fields and callbacks in a unified Matlab window. <i><b>uiinspect</b></i> works on a very wide variety of inputs: Matlab/Java/Dot-Net class names and class objects; COM/DCOM objects, Handle Graphics handles etc.<br />
In essence, <i><b>uiinspect</b></i> incorporates the information presented by the following built-in Matlab functions: <i><b>inspect</b></i>, <i><b>get</b></i>, and <i><b>methodsview</b></i>. <i><b>uiinspect</b></i> also presents additional aspects that are not available in any built-in Matlab function (for example, inheritance information, undocumented hidden properties, properties meta-data, grouping of callbacks by type).<br />
<i><b>uiinspect</b></i> displays hidden properties and fields that are not normally displayed in Matlab (see my related <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties/">getundoc</a> utility). Property meta-data such as type, accessibility, visibility and default value are also displayed. Object properties and callbacks may be modified interactively within the <i><b>uiinspect</b></i> window.<br />
Of over 40 utilities that I have so-far submitted to the File Exchange, <i><b>uiinspect</b></i> is one of my most complex (together with <a target="_blank" href="/articles/findjobj"><i><b>findjobj</b></i></a>). It has undergone 24 revisions since its initial release in 2007. The latest revision has nearly 3000 source-code lines, of which 75% are code lines, 20% are comment lines and the rest are empty spacer lines. That&#8217;s a pretty complex utility to describe, and it relies on plenty of undocumented aspects, so today&#8217;s post will only highlight the important aspects. Readers are more than welcome to have a look at the source code for additional details. It is pretty-well documented, if I may say so myself.<br />
<span id="more-3477"></span></p>
<h3 id="syntax">Usage syntax</h3>
<p>The basic syntax is:</p>
<pre lang='matlab'>hFig = uiinspect(handle)</pre>
<p>Examples:</p>
<pre lang='matlab'>
hFig = uiinspect(0);                         % the root handle
hFig = uiinspect(handle(0));
hFig = uiinspect(gcf);                       % current figure
hFig = uiinspect(handle(gcf));
uiinspect('java.lang.String');               % Java classname
uiinspect(java.lang.String('yes'));          % Java object
uiinspect(get(gcf,'JavaFrame'));             % Java object
uiinspect(classhandle(handle(gcf)));         % UDD class object
uiinspect(findprop(handle(gcf),'MenuBar'));  % UDD property
uiinspect(actxserver('Excel.Application'));  % COM object
uiinspect(Employee)                          % Matlab class object
uiinspect(?handle)                           % Matlab metaclass object
uiinspect('meta.class')                      % Matlab class name
uiinspect(System.DateTime.Now)               % Dot-Net object
</pre>
<p><i><b>uiinspect</b></i> returns a handle to the created figure window. <i><b>uiinspect</b></i> opens a regular Matlab figure window which may be accessed via hFig (unlike Matlab&#8217;s <i><b>methodsview</b></i> and <i><b>inspect</b></i> functions which open Java frame that is not accessible from Matlab).<br />
Unlike Matlab&#8217;s functions, multiple <i><b>uiinspect</b></i> windows can be opened simultaneously, for different objects. The differentiation is done based on figure title, which contains the inspected object&#8217;s name (if available) and its class &#8211; reinspecting the same object will reuse the existing figure window, but in all other cases a new figure window will be created.</p>
<h3 id="panels">Main panels</h3>
<p><i><b>uiinspect</b></i> includes the following information panels, that shall be described separately below:</p>
<ul>
<li>Class information (including superclasses, if applicable)</li>
<li>Methods (for objects) or graphic handle hierarchy (for Handle Graphics)</li>
<li>Callbacks (where applicable)</li>
<li>Inspectable properties</li>
<li>Other properties plus full meta-data (where applicable)</li>
</ul>
<p>The panels are fully resizable. We can drag the divider lines up/down or left/right and the contents automatically adjust accordingly. Each panel has a minimal viewable width/height, and the dividers cannot be dragged to squeeze the panels below these minimums &#8211; they can only be minimized, which hides the relevant panel entirely. To minimize a panel, simply click the relevant small arrow mark on the divider. The opposite arrow mark next to it maximizes the panel, effectively minimizing the panel on the other side. Once minimized/maximized, the divider can be restored by simply clicking it once, or by dragging it (again, panel minimum sizes apply).<br />
<i><b>uiinspect</b></i> only uses Java panels, so implementing the dividers required use of the simple <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/splitpane.html">JSplitPane</a>. In a general case where we might wish to embed Matlab graphs in one of the side panels, we would need to employ a more sophisticated solution (see my <a target="_blank" href="/articles/uisplitpane/">UISplitPane</a> utility).</p>
<h3 id="class">Class information</h3>
<p>The top-left panel displays a label with information about the object&#8217;s class and super-classes inheritance (where applicable).<br />
The class name itself is hyper-linked to the class&#8217;s documentation: if this is a standard Java class, then to the official online javadoc for this class which opens up in Matlab&#8217;s internal web browser. In fact, since different Matlab releases use different JVM versions (1.3 through 1.6), the link points to the documentation page corresponding to the JVM version actually used.<br />
If the class is non-Java, the hyperlink displays the class&#8217;s help section in Matlab&#8217;s Command Window / console. The panel&#8217;s tooltip displays the same information in a slightly different manner.<br />
The hyperlink in the label is actually an optical illusion. In fact, the entire label is hyper-linked, and clicking any part of it will display the relevant documentation (a similar optical illusion is used to display the hyperlink at the footer of the utility window). The illusion is achieved using <a target="_blank" href="/articles/html-support-in-matlab-uicomponents/">Matlab&#8217;s HTML formatting</a>, where the part of the label string consisting of the class name is underlined. The cursor was dynamically modified to a pointed hand-finger when the mouse hovers over the label, using the following simple Java-based command:</p>
<pre lang='matlab'>methodsLabel.setCursor(java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));</pre>
<p>Special treatment is done to extract the class&#8217;s superclass, the interfaces that it implements and any possible class qualifiers (for example, &#8220;final&#8221;).<br />
For those interested to dig within the code, all this is done in <i><b>uiinspect</b></i>&#8216;s <i>getMethodsPane</i> function.<br />
Next to the class label, a checkbox is presented (&#8220;Extra&#8221;). Clicking this checkbox displays additional meta-data information (qualifiers, interrupts and inheritance) in the methods pane beneath. Not all classes have all these extra meta-data fields &#8211; only the relevant extra meta-information fields are displayed. If there are is extra meta-data, then the checkbox is not displayed. This is done in the <i>getMethodsTable</i> function.</p>
<h3 id="methods">Methods or HG hierarchy panel</h3>
<p>The utility&#8217;s main panel displays either a table of methods (functions) for a class object, or a tree hierarchy for an HG handle.</p>
<h4 id="class-methods">Class object methods</h4>
<p>The methods table takes the information from the <i>getObjMethods</i> function, which is an adaptation of Matlab&#8217;s built-in <i><b>methodsview</b></i> function. Part of the adaptation is to hyperlink all class references (used in the methods&#8217; inputs, outputs and meta-data), such that clicking them will open new corresponding <i><b>uiinspect</b></i> windows.<br />
<figure style="width: 468px" class="wp-caption alignright"><img decoding="async" alt="Class object methods panel" src="https://undocumentedmatlab.com/images/uiinspect_methods.gif" title="Class object methods panel" width="468" height="219" /><figcaption class="wp-caption-text">Class object methods panel</figcaption></figure><br />
The methods data is displayed within a non-editable Java table (in the <i>getMethodsTable</i> function) that auto-resizes the columns. The table columns are sortable, even sortable on multiple columns by CTRL-clicking (<i><b>methodsview</b></i> allows only simple sorting). This is done using JIDE&#8217;s <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/com/jidesoft/grid/TreeTable.html">TreeTable</a> component. The table is placed within a scroll-pane having <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html#scrollbars">automatic scrollbars</a> that only appear as needed.<br />
The table&#8217;s <b>MouseMovedCallback</b> property is set to <i>tbMouseMoved</i>, which updates the mouse cursor (either regular or pointed finger) based on the current mouse position in the table (whether over a hyperlinked cell or not).<br />
The table&#8217;s <b>MousePressedCallback</b> property is set to <i>tbMousePressed</i>, which opens new <i><b>uiinspect</b></i> figure windows for the hyperlinked classes (if any) in the clicked cell.</p>
<h4 id="HG-hierarchy">HG hierarchy tree</h4>
<p>For HG handles, <i>getHandleTree</i> creates a Java tree that displays the hierarchy of HG children (as recursively reported by any HG handle&#8217;s <b>Children</b> property). For convenience, I have chosen to use the built-in component <code>com.mathworks.hg.peer.UITreePeer</code> that underlies the built-in <a target="_blank" href="/articles/uitree/"><i><b>uitree</b></i></a> function. For performance reasons, the tree is not fully evaluated: the inspected handle&#8217;s <b>Parent</b> is set as the tree&#8217;s <b>Root</b>. The root node is expanded to get all the parent&#8217;s <b>Children</b> (i.e., the inspected handle&#8217;s siblings), and then the inspected handle&#8217;s tree node is again expanded to display its direct descendents.<br />
<figure style="width: 283px" class="wp-caption alignright"><img decoding="async" alt="Normal dynamic HG handle tooltip" src="https://undocumentedmatlab.com/images/uiinspect_HG_tooltip1.gif" title="Normal dynamic HG handle tooltip" width="283" height="115" /><figcaption class="wp-caption-text">Normal dynamic HG handle tooltip</figcaption></figure><br />
A <b>MouseMovedCallback</b> is set on the tree to process mouse hover events in the <i>treeMouseMovedCallback</i> function. This function updates the tree tooltip dynamically, in the sense that it presents a different tooltip for different handles (tree nodes).<br />
Invalid HG handles (this can happen if the HG handle was deleted since the time that <i><b>uiinspect</b></i> generated the tree) are displayed with a special warning message.<br />
<figure style="width: 350px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Invalid HG handle tooltip" src="https://undocumentedmatlab.com/images/uiinspect_HG_tooltip2.gif" title="Invalid HG handle tooltip" width="350" height="44" /><figcaption class="wp-caption-text">Invalid HG handle tooltip</figcaption></figure><br />
This dynamic tree behavior is achieved by storing the relevant handle information in the <b>UserData</b> of the different tree nodes. Unfortunately, starting in R2012a, Matlab has made a change in the internal support of Java objects, and the <b>UserData</b> property is no longer available. Such a case is detected and the data is stored in the tree nodes&#8217; <b>ApplicationData</b> property instead (using <i><b>setappdata</b>(node,&#8217;userdata&#8217;,&#8230;)</i> ).<br />
<figure style="width: 630px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Dynamic context (right-click) menu" src="https://undocumentedmatlab.com/images/uiinspect3.gif" title="Dynamic context (right-click) menu" width="630" height="488" /><figcaption class="wp-caption-text">Dynamic context (right-click) menu</figcaption></figure><br />
A <b>MousePressedCallback</b> is set on the tree to process context (right-click) events in the <i>treeMousePressedCallback</i> function. The context-menu is also dynamic, in the sense that it presents a different context menu for different handles (tree nodes), again based on their user-data.<br />
Left-clicking a node is not processed by <i>treeMousePressedCallback</i>, but rather by the tree&#8217;s <b>NodeSelectedCallback</b> which is processed in <i>nodeSelected</i>, and by <b>NodeExpandedCallback</b> which is processed by <i>nodeExpanded</i>. <i>nodeSelected</i> reloads <i><b>uiinspect</b></i> for the selected handle; <i>nodeExpanded</i> merely displays the expanded handle&#8217;s children.<br />
Since the &#8216;+&#8217; sign (which triggers <i>nodeExpanded</i>) and the handle icon (which triggers <i>nodeSelected</i>) are so close, we should be careful to click the &#8216;+&#8217;, otherwise the entire <i><b>uiinspect</b></i> window will reload the tree based on the clicked node&#8230; If anyone has a good idea how to solve this dilemma, then I&#8217;m all ears.<br />
Like the methods table, the tree is also placed in a dynamic scroll-pane that displays scrollbars only as needed.</p>
<h3 id="callbacks">Callbacks panel</h3>
<p>The callbacks panel, computed in <i>getCbsData</i> is based on a reflection of the object&#8217;s data as reported by the undocumented built-in <i><b>classhandle</b></i> function. I aggregate all the object&#8217;s events, as well as all the object property names that end with &#8216;Fcn&#8217; or &#8216;Callback&#8217;. This takes care (I hope) of all the different manners by which different kinds of objects raise events that are trappable in Matlab callbacks. Specifically, it takes care of Java/Matlab classes as well as HG handles and COM objects. If anyone thinks that I have forgotten something, please let me know.<br />
The <i>getCbsPane</i> function then displays the callbacks data (callbacks&#8217; property name and value) in a Java table (JIDE <a target="_blank" href="/articles/jide-property-grids/">PropertyTable</a>, JIDE TreeTable, or failing those a simple JTable).<br />
<figure style="width: 551px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Modifiable object callbacks" src="https://undocumentedmatlab.com/images/uiinspect_callbacks.gif" title="Modifiable object callbacks" width="551" height="337" /><figcaption class="wp-caption-text">Modifiable object callbacks</figcaption></figure><br />
The callbacks are automatically grouped by name into logical groups (in <i>getTreeData</i>). For example, all callbacks whose names start with &#8220;Mouse*&#8221; are grouped in the &#8220;Mouse callbacks&#8221; group. The last group is always called &#8220;Other callbacks&#8221; and contains all callbacks for which a matching sibling callback has not been found. The groups are automatically collapsed by default; if only a single group is found then this group is automatically opened (for example, in the case of <i><b>uiinspect</b>(0)</i> ).<br />
The callbacks table&#8217;s toolbar enables displaying the callbacks by groups or sorted alphabetically. It also has &#8220;expand&#8221; and &#8220;collapse&#8221; icons that affect all the groups.<br />
A checkbox next to the table&#8217;s toolbar enables hiding <a target="_blank" href="/articles/uicontrol-callbacks/">standard Java Swing callbacks</a>. This is important when we inspect Java controls and only wish to see its unique callbacks. When using this checkbox, red Java exceptions are sometimes displayed in the Matlab console &#8211; these are harmless and you can safely ignore them (I hope to find a way to prevent them one day).<br />
The table&#8217;s right column displays the callback properties values (if available). This column is editable and we can interactively modify any callback&#8217;s property. As shown, we can enter callback value in either of Matlab&#8217;s supported formats: string, function handle and (for non-COM objects only!) a cell array of function handle and additional data. An error message will be displayed if the callback value is invalid or cannot be set for some reason.<br />
If it is determined that there are no callbacks, then the callbacks panel is automatically minimized, to enable maximum space for the methods panel above it.</p>
<h3 id="inspector">Properties inspector panel</h3>
<p>The properties inspection panel, prepared in <i>getPropsPane</i>, is actually composed of two separate panes: the top pane uses the built-in Matlab component <code>com.mathworks.mlwidgets.inspector.PropertyView</code>, which in turn uses JIDE&#8217;s <a target="_blank" href="/articles/jide-property-grids/">PropertyTable</a>. <code>PropertyView</code> is the same component used by Matlab&#8217;s standard <i><b>inspect</b></i> function (that&#8217;s how I came to know it, if anyone wonders).<br />
<figure style="width: 351px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uiinspect's property inspector table" src="https://undocumentedmatlab.com/images/PropertyTable.gif" title="uiinspect's property inspector table" width="351" height="216" /><figcaption class="wp-caption-text">uiinspect's property inspector table</figcaption></figure><br />
The benefit of using Matlab&#8217;s <code>PropertyView</code> component rather than JIDE&#8217;s <code>PropertyTable</code> is that <code>PropertyView</code> has the very useful method <i>setObject</i> which I use to point the component at the inspected object, which automatically infers its non-hidden properties and updates the table, saving me a lot of work.<br />
There are two drawbacks of using Matlab&#8217;s <code>PropertyView</code>:</p>
<ul>
<li><code>PropertyView</code> only displays non-hidden properties. One day when I have time, I intent to add the hidden properties to the resulting JIDE <code>PropertyTable</code>. But for now it only shows non-hidden properties.</li>
<li><code>PropertyView</code> causes a Matlab crash on some Matlab releases, in case <i><b>dbstop if error</b></i> is active (this can be replicated using Matlab&#8217;s standard <i><b>inspect</b></i>). I therefore regrettably need to disable this specific <i><b>dbstop</b></i>.</li>
</ul>
<p>I&#8217;ve been meaning to do these two fixes ever since I released <i><b>uiinspect</b></i> back in 2007, but for now that&#8217;s the way it is&#8230;<br />
The properties data is retrieved via the <i>getPropsData</i> function. This function uses the built-in Matlab functions <i><b>meta.class.fromName</b>(className)</i> and <i><b>metaclass</b>(classObject)</i> to get the class handle of Matlab classes (in <i>getMetaClass</i>); similarly, <i>loadClass</i> loads the class definition for a Java class. I inspect these class handles for their contained properties. I then use the <i><b>fieldnames</b></i> function to add static class fields, which are not standard properties (for example, &#8220;RED&#8221; is a static field of the <code>java.awt.Color</code> class).<br />
From the class handle, I retrieve the full definition of each property. This includes meta-data such as whether the property is regular or hidden (undocumented); settable or not; gettable or not; and any additional qualifiers (e.g., Sealed, Dependent, Constant, Abstract, Transient, Default (factory) value).<br />
<figure style="width: 450px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Object properties tooltip" src="https://undocumentedmatlab.com/images/uiinspect_properties1.gif" title="Object properties tooltip" width="450" height="297"/><figcaption class="wp-caption-text">Object properties tooltip</figcaption></figure><br />
We now have a list of all properties and static fields, and this is used to display the entire properties data in the properties panel&#8217;s title (&#8220;Inspectable object properties&#8221;) tooltip. This tooltip, created in <i>updateObjTooltip</i> and <i>getPropsHtml</i>, uses some fancy HTML formatting to display all the object&#8217;s properties and values, color- and font-style-coded to show which of the properties is read-only, hidden, undefined etc.<br />
<figure style="width: 495px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="The 'Other properties' meta-data table" src="https://undocumentedmatlab.com/images/uiinspect_properties2.gif" title="The 'Other properties' meta-data table" width="495" height="317" /><figcaption class="wp-caption-text">The 'Other properties' meta-data table</figcaption></figure><br />
The entire information is also displayed in the properties meta-data pane (&#8220;Other properties&#8221;) beneath JIDE&#8217;s inspector pane. Here we use a simple Java table to display the information in color-coding (gray for read-only properties; blue for static fields; red for irretrievable properties).<br />
Separate checkboxes enable displaying all properties (by default only the properties that are NOT displayed in JIDE&#8217;s inspector table are displayed); and whether or not to display the extra meta-data in the properties table (by default only the property name and current value are displayed).<br />
In some cases (e.g., Dot-Net objects), Matlab&#8217;s inspector does not know how to extract the property-bean information and so the <code>PropertyView</code> inspector is not shown, only the &#8220;other properties&#8221; table.<br />
Both JIDE&#8217;s inspector table and the &#8220;other properties&#8221; table enable the user to modify existing values. Note that in some cases Matlab prevents interactive update of some properties, and in some other cases I have seen Matlab hang when trying to update a few specific properties. But in most cases updating the value does work as expected.<br />
The combination of the inspector table, the meta-data table and the tooltip, enable users to fully understand the accessible properties of the inspected object. Of course, it would have been much better to merge the JIDE inspector table with the hidden properties (=additional rows) and meta-data (=additional columns). But let&#8217;s leave something for the future, shall we?</p>
<h3 id="update">Auto-update mechanism</h3>
<p><figure style="width: 519px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uiinspect auto-update notice" src="https://undocumentedmatlab.com/images/uiinspect_update.gif" title="uiinspect auto-update notice" width="519" height="190" /><figcaption class="wp-caption-text">uiinspect auto-update notice</figcaption></figure><br />
<i><b>uiinspect</b></i> employs the same auto-update background mechanism used by <i><b>findjobj</b></i> &#8211; after presenting the GUI, the utility silently checks the File Exchange webpage to see whether any newer version of this utility has been uploaded. If so, then a popup notice is presented with the date and description of the latest version. The popup enables users to download the newer version into their Matlab path, or skip. There is also an option to skip the update and not to remind ever again.<br />
I find this background auto-update mechanism quite useful and generic. In fact, I uploaded it as a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/39993-checkVersion">separate File Exchange utility</a> today, following <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/pick/2012/12/14/a-conversation-about-managing-file-exchange-downloads/#comment-17358">Brett Shoelson&#8217;s suggestion</a> last month. You can find the underlying code in the <i>checkVersion</i> function.</p>
<h3 id="TODO">TODO</h3>
<ul>
<li>cleanup internal functions, remove duplicates etc.</li>
<li>link property objects to another <i><b>uiinspect</b></i> window for these objects</li>
<li>display object children (&#038; link to them) &#8211; COM/Java</li>
<li>find a way to merge the other-properties table with the inspector table (hidden props + meta-data)</li>
<li>find a way to use the inspector without disabling <i><b>dbstop if error</b></i></li>
<li>Fix: some fields generate a Java Exception from: <code>com.mathworks.mlwidgets.inspector.PropertyRootNode$PropertyListener$1$1.run</code></li>
<li>Fix: using the &#8220;Hide standard callbacks&#8221; checkbox sometimes issues Java Exceptions on the console</li>
<li>Fix: In HG tree view, sometimes the currently-inspected handle is not automatically selected</li>
</ul>
<p>I would be happy if anyone can help with any of these.</p>
<h3 id="conclusion">Conclusion</h3>
<p>I believe that this has been my longest blog post ever; certainly the one that I have labored most over. This correlates well with the <i><b>uiinspect</b></i> utility, which has been one of my most complex tasks. I&#8217;m guessing I must have invested 100-200 man-hours developing and improving it over the years.<br />
I hope you find <i><b>uiinspect</b></i> as useful and as fun as I do. I believe that its source-code is certainly worth reading if you are interested in any advanced Matlab GUI programming, showing how Java GUI components can be combined in Matlab. Go ahead and <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect">download <i><b>uiinspect</b></i></a> from the Matlab file Exchange.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uiinspect">uiinspect</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/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>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-gui-display-container-hierarchy" rel="bookmark" title="FindJObj GUI &#8211; display container hierarchy">FindJObj GUI &#8211; display container hierarchy </a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/propertiesgui" rel="bookmark" title="propertiesGUI">propertiesGUI </a> <small>propertiesGUI is a utility that presents property-value structs in a convenient table format, useful in Matlab GUIs. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/uiinspect/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Fixing Matlab&#039;s actxserver</title>
		<link>https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=fixing-matlabs-actxserver</link>
					<comments>https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 19 Dec 2012 18:00:32 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[ActiveX]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3416</guid>

					<description><![CDATA[<p>Matlab's COM (ActiveX) server behavior can be fixed in a couple of useful manners. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver">Fixing Matlab&#039;s actxserver</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/fixing-a-java-focus-problem" rel="bookmark" title="Fixing a Java focus problem">Fixing a Java focus problem </a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-compiled-apps-startup" rel="bookmark" title="Speeding up compiled apps startup">Speeding up compiled apps startup </a> <small>The MCR_CACHE_ROOT environment variable can reportedly help to speed-up deployed Matlab executables....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab&#8217;s built-in <i><b>actxserver</b></i> function provides access to <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Component_Object_Model">COM</a>/<a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Distributed_Component_Object_Model">DCOM</a> server applications on Microsoft Windows platforms. This enables us, for example, to open a Microsoft Office document programmatically, and modify it from within Matlab. This in turn can be used, for example, to prepare professional PDF reports, relying on Office&#8217;s ability to save documents in PDF format. Alternately, we could programmatically update cell formatting (colors, fonts, borders etc.) and embed images and graphs in an Excel workbook &#8211; something that the standard <i><b>xlswrite</b></i> cannot do (my <i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15192-officedoc-read-write-format-ms-office-docs-xls-doc-ppt">officedoc</a></b></i> utility does this, using the same COM interface).<br />
Note: For some reason, COM servers are called an <i>ActiveX server</i> in Matlab, although the term <i>ActiveX</i> is normally used for <i>clients</i> (i.e., controls), for which we have the <i><b>actxcontrol*</b></i> set of built-in functions.<br />
Today I will focus on two changes that I made to Matlab&#8217;s built-in <i><b>actxserver</b></i> function:</p>
<h3 id="reusing">Reusing an active server <i> (no pun intended&#8230;)</i></h3>
<p>By default, <i><b>actxserver</b></i> starts a new instance of the specified COM server whenever it is called. Sometimes this is indeed useful. However, I find that in the vast majority of cases, I actually want to reuse an existing server instance if it is currently running. For example, it is <u>much</u> faster and more memory-efficient to open an Excel workbook file in an existing Excel process, than to open it in a new dedicated process.<br />
In R2007a, Matlab introduced the <i><b>actxGetRunningServer</b></i> function. Unfortunately, it did not see fit to set it as the default behavior for <i><b>actxserver</b></i>, nor even as an optional additional parameter (although MathWorks *did* change the <i><b>actxserver</b></i> function in that very same release, to accept a custom interface parameter). Users need to change their programs to first call <i><b>actxGetRunningServer</b></i>, check whether it works or fails, and then call <i><b>actxserver</b></i> if it fails (meaning that a server process is not currently running and a new one needs to be started):</p>
<pre lang='matlab'>
% Try to reuse an existing COM server instance if possible
try
    hServer = actxGetRunningServer('excel.application');
    % no crash so probably succeeded to connect to a running server
catch
    % Never mind - continue normally to start the COM server and connect to it
    hServer = actxserver('excel.application');
end
</pre>
<p>This is downright silly, I must say.<br />
<span id="more-3416"></span><br />
Moreover, all the existing user and Matlab code that uses <i><b>actxserver</b></i> will continue to start a new server instance rather than reuse existing ones. For example, the widely-used <i><b>xlsread</b></i> and <i><b>xlswrite</b></i> functions.<br />
Instead of fixing Matlab&#8217;s installed <i>actxserver.m</i> file, which could be problematic when deploying applications to end-users, I created a copy of <i>actxserver.m</i> somewhere in my user folders that is high on the Matlab path. This way I can modify the file and bundle it with any application that I send to clients. The change to this file is simply to add a variant of the code above at the very top of the <i>actxserver.m</i> file, as follows (the new lines are highlighted):</p>
<pre lang='matlab' highlight="9-15">
function h = actxserver(progID, varargin)
%ACTXSERVER Creates a COM Automation server.
...
% Copyright 2006-2007 The MathWorks, Inc.
% $Revision: 1.8.6.12 $ $Date: 2011/08/13 17:30:50 $
error(nargchk(1, 5, nargin, 'struct'));
% Yair 17/5/2009: Try to reuse an existing COM server instance if possible
try
    h = actxGetRunningServer(progID);
    return;  % no crash so probably succeeded - return
catch
    % Never mind - continue normally to start the COM server and connect to it
end
machinename = '';
interface = 'IDispatch';
...
</pre>
<p>This simple change means that all exiting code, including Matlab&#8217;s built-in <i><b>xlsread</b></i> and <i><b>xlswrite</b></i> functions, now try to reuse a running COM server process if possible, starting a new one only if this fails. The code is fault-tolerant in that it also works on old Matlab releases where the <i><b>actxGetRunningServer</b></i> is not available.</p>
<h3 id="fix">Fix of the progID</h3>
<p>The <i>%matlabroot%/toolbox/matlab/winfun/private/newprogid.m</i> function, a private function used by <i><b>actxserver</b></i>, normalizes COM program identifiers (progIDs), which is the string used to locate the COM server. Unfortunately, until R2011a (or specifically, when this was fixed by some MathWorker on June 10, 2010), this function had a bug that caused the normalization to fail. In order to correct this, I simply added the fixed function to the bottom of my modified <i>actxserver.m</i> file:</p>
<pre lang='matlab'>
% Taken from: [matlabroot '\toolbox\matlab\winfun\private\newprogid.m']
function convertedProgID = newprogid(progID)
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 1.1.8.5 $ $Date: 2004/04/15 00:07:00 $
convertedProgID = lower(progID);  % Yair: in the new version (after 2010/06/10) this line is missing i.e. case-sensitive progID
convertedProgID = regexprep(convertedProgID, '_', '__');  % Yair 17/5/2009: was progId - probably a bug
convertedProgID = regexprep(convertedProgID, '-', '___');
convertedProgID = regexprep(convertedProgID, '\.', '_');
convertedProgID = regexprep(convertedProgID, ' ', '____');
convertedProgID = regexprep(convertedProgID, '&', '_____');
</pre>
<p>Note that when MathWorks fixed <i>%matlabroot%/toolbox/matlab/winfun/private/newprogid.m</i> in 2010, they removed the conversion of progID to lower-case, making it case-sensitive. In my modified version above, I have kept the older conversion to lowercase for case-insensitivity.</p>
<h3 id="seminar">Public-service announcements</h3>
<p><center><figure style="width: 350px" class="wp-caption alignright"><a target="_blank" rel="nofollow" href="http://www.johnbryce.co.il/content/%D7%99%D7%95%D7%9D-%D7%A4%D7%AA%D7%95%D7%97-%D7%90%D7%9C%D7%A7%D7%98%D7%A8%D7%95%D7%A0%D7%99%D7%A7%D7%94/?source=divur_martze"><img loading="lazy" decoding="async" alt="Matlab open training day (Israel) - click for details" src="https://undocumentedmatlab.com/courses/Matlab_open_day_350x225a.png" title="Matlab open training day (Israel) - click for details" width="350" height="225"/></a><figcaption class="wp-caption-text">Matlab open training day (Israel) - click for details</figcaption></figure></center><br />
Readers in Israel are invited to attend a free training seminar that I will present on advanced Matlab topics in Herzliya, on Tuesday Jan 8, 2013. The seminar is free, but requires registration. <a target="_blank" rel="nofollow" href="http://www.johnbryce.co.il/content/%D7%99%D7%95%D7%9D-%D7%A4%D7%AA%D7%95%D7%97-%D7%90%D7%9C%D7%A7%D7%98%D7%A8%D7%95%D7%A0%D7%99%D7%A7%D7%94/?source=divur_martze">Additional details here</a>. I will speak in Hebrew, but the presentation will be in English and I will be happy to answer questions in English.<br />
I wish to point readers&#8217; attentions to the recent <a target="_blank" rel="nofollow" href="http://blog.accelereyes.com/blog/2012/12/12/exciting-updates-from-accelereyes/">announcement</a> by AccelerEyes and MathWorks, that they will now merge their parallel-processing solutions into Matlab&#8217;s product line. I assume this also means an out-of-court settlement of MathWorks&#8217; <a target="_blank" rel="nofollow" href="http://news.priorsmart.com/mathworks-v-accelereyes-l4cm/">patent-infringement lawsuit</a>. On the one hand, this is bad news for competition, removing Matlab PCT&#8217;s major competitor from the market. On the other hand, it could mean improved PCT/DCS products, merging Jacket&#8217;s superior performance and functionality directly within Matlab. If I may venture a guess, 2013 will herald a better, faster, more integrated parallel computing solution for Matlab, but we should probably (and quite sadly) say goodbye to Jacket&#8217;s price levels. Such collaborations, generally portrayed as exciting for consumers, are typically much more exciting for the respective shareholders&#8230;<br />
This blog will now take a short winter break, and will return following the New-Year. Happy Holidays/New-Year everyone! Let this upcoming year be another year filled with discoveries, innovation and success!<br />
&nbsp;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver">Fixing Matlab&#039;s actxserver</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/fixing-a-java-focus-problem" rel="bookmark" title="Fixing a Java focus problem">Fixing a Java focus problem </a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-compiled-apps-startup" rel="bookmark" title="Speeding up compiled apps startup">Speeding up compiled apps startup </a> <small>The MCR_CACHE_ROOT environment variable can reportedly help to speed-up deployed Matlab executables....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>xlswrite for Mac, Linux</title>
		<link>https://undocumentedmatlab.com/articles/xlswrite-for-mac-linux?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=xlswrite-for-mac-linux</link>
					<comments>https://undocumentedmatlab.com/articles/xlswrite-for-mac-linux#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 02 Aug 2012 09:44:35 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[ActiveX]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[File Exchange]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3041</guid>

					<description><![CDATA[<p>Several Matlab utilities enable reading/writing spreadsheet data (including XLS files) in Macs, Linux. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/xlswrite-for-mac-linux">xlswrite for Mac, Linux</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/jfreechart-graphs-and-gauges" rel="bookmark" title="JFreeChart graphs and gauges">JFreeChart graphs and gauges </a> <small>JFreeChart is an open-source charting library that can easily be integrated in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver" rel="bookmark" title="Fixing Matlab&#039;s actxserver">Fixing Matlab&#039;s actxserver </a> <small>Matlab's COM (ActiveX) server behavior can be fixed in a couple of useful manners. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jboost-integrating-an-external-java-library-in-matlab" rel="bookmark" title="JBoost &#8211; Integrating an external Java library in Matlab">JBoost &#8211; Integrating an external Java library in Matlab </a> <small>This article shows how an external Java library can be integrated in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-line-position-in-edit-box-uicontrol" rel="bookmark" title="Setting line position in an edit-box uicontrol">Setting line position in an edit-box uicontrol </a> <small>Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Numerous Matlab users have <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/152206">expressed frustration</a> over the years at the fact that the <i><b>xlswrite</b></i> function, used for saving/updating Excel files, is only supported on the Windows platform. Matlab uses Excel COM to implement <i><b>xlswrite</b></i> functionality, and since COM is a Windows-specific technology, <i><b>xlswrite</b></i> does not work on non-Windows platforms.<br />
In such cases, Matlab users normally save the data into a CSV (comma-separated values) file, using the built-in <i><b>csvwrite</b></i> or <i><b>dlmwrite</b></i> functions, or File-Exchange utilities such as <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/19149-any2csv">Any2CSV</a>. This enables saving the data, but does not enable saving formatting information or graphic objects (e.g., plots or images). As a side note, <i><b>xlswrite</b></i> also does not allow saving formatting information or graphic objects, but at least on Windows we can use direct COM to add them (or use my <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15192-officedoc">OfficeDoc</a> utility).</p>
<h3 id="Java">Java solutions for spreadsheet access</h3>
<p>Luckily, the community of Java developers, which is an order of magnitude larger than the Matlab community, has developed several utilities that we can easily use in Matlab to implement <i><b>xlswrite</b></i>&#8216;s functionality on Macs, Linux, and wherever else Matlab may run &#8211; even Windows, if we really wish. Most articles on this website that deal with Java focus on its GUI aspects, i.e., how to use Java to improve Matlab&#8217;s plain-vanilla appearance/behavior. But Java is in fact a very broad programming platform that has an enormous repository of non-GUI solutions: networking, database support, data structures, computational algorithms, etc. etc. &#8211; and a huge number of them are open-source. Unlike Java&#8217;s GUI goodies, these Java packages, being non-GUI in nature, are fully supported by Matlab.<br />
The Excel spreadsheets support, and Office support in general, is just another example of the wide range of non-GUI packages available in Java. In fact there are full-fledged Office lookalikes written in Java (most notably the open-source <a target="_blank" rel="nofollow" href="http://www.openoffice.org">OpenOffice</a>). We can either use these applications directly, or interact with them from Matlab (via Java), just as we can interact with Excel on Windows.<br />
There are several Java packages that enable reading and writing spreadsheet data, without the full-blown Office support. One such open source project is the <a target="_blank" rel="nofollow" href="http://incubator.apache.org/odftoolkit/">ODF (Open Document Foundation) Toolkit</a>, which has plenty of online resources. In 2010 a Matlab user contributed a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28411">utility</a> to use the ODF Java package for reading and writing ODF-format spreadsheets (*.ods). Other users have also <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/18222-load-open-document-spreadsheets">provided</a> ODF utilities for Matlab.<br />
Using ODF is excellent and cross-platform, but does not solve the Excel problem directly, because the ODF format is incompatible with the XLS format. We can use another open-source Java package, <a target="_blank" rel="nofollow" href="http://jexcelapi.sourceforge.net/">JExcelApi</a>, for this. JExcelApi is relatively easy to use and has several online tutorials (<a target="_blank" rel="nofollow" href="http://www.vogella.com/articles/JavaExcel/article.html">example1</a>, <a target="_blank" rel="nofollow" href="http://www.andykhan.com/jexcelapi/tutorial.html">example2</a>), although it is not as widely used as ODF.<br />
Another open-source Java package that can be used to directly read and write XLS files is <a target="_blank" rel="nofollow" href="http://poi.apache.org/">Apache POI</a>. An informal comparison of POI and JExcelApi can be found <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/4752456/memory-efficient-java-library-to-read-excel-files">here</a>.</p>
<h3 id="xlwrite"><i><b>xlwrite</b></i></h3>
<p>Very recently, <a target="_blank" rel="nofollow" href="http://aaaic.com/Our_People.html">Marin Deresco</a> has posted a Matlab utility called <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/37560-xlwrite"><i><b>xlwrite</b></i></a> that uses JExcelApi for implementing an <i><b>xlswrite</b></i> variant that can be used on all Matlab platforms.<br />
<span id="more-3041"></span><br />
After downloading <i><b>xlwrite</b></i>, we need to add its two contained JAR files (<i>jxl.jar, MXL.jar</i>) to the Java classpath:</p>
<pre lang='matlab'>
javaaddpath('C:/Yair/Utils/JExcelAPI/jxl.jar')
javaaddpath('C:/Yair/Utils/JExcelAPI/MXL.jar')
</pre>
<p>We can now use <i><b>xlwrite</b></i> to store data in a real *.xls file:</p>
<pre lang='matlab'>xlwrite('my_data.xls', magic(3))</pre>
<p><i><b>xlwrite</b></i> has similar syntax and inputs to Matlab&#8217;s <i><b>xlswrite</b></i>. It can also write 3-d arrays (which <i><b>xlswrite</b></i> cannot), of cell and double type (the third dimension is simply stored in separate worksheets).<br />
Note: Matlab&#8217;s decimal separator is &#8216;.&#8217; &#8211; in order to be able to work with exported data on Macs, Mac users may need to change Mac decimal separator preferences. To do so you need to go to System Preferences &gt; International &gt; Formats and click on Customize button in the number zone, then type &#8216;.&#8217; in the required field.<br />
<i><b>xlwrite</b></i> is a real working solution. However, it may need further refinements, that will hopefully be added in future updates to this utility:</p>
<ul>
<li>automatically add the <i><b>javaaddpath</b></i> commands to <i><b>xlwrite</b></i> so that users won&#8217;t need to do them</li>
<li>manage Java heap space, as Java heap memory saturates for large arrays exported many times (possible memory leak)</li>
<li>format dates and strings, as all numbers appear as text in Excel</li>
<li>optimize performance (the culprit appears to be a non-vectorized <i>Cell2JavaString</i> function)</li>
<li>include formatting and other goodies that the current <i><b>xlswrite</b></i> does not</li>
</ul>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/xlswrite-for-mac-linux">xlswrite for Mac, Linux</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/jfreechart-graphs-and-gauges" rel="bookmark" title="JFreeChart graphs and gauges">JFreeChart graphs and gauges </a> <small>JFreeChart is an open-source charting library that can easily be integrated in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver" rel="bookmark" title="Fixing Matlab&#039;s actxserver">Fixing Matlab&#039;s actxserver </a> <small>Matlab's COM (ActiveX) server behavior can be fixed in a couple of useful manners. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jboost-integrating-an-external-java-library-in-matlab" rel="bookmark" title="JBoost &#8211; Integrating an external Java library in Matlab">JBoost &#8211; Integrating an external Java library in Matlab </a> <small>This article shows how an external Java library can be integrated in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-line-position-in-edit-box-uicontrol" rel="bookmark" title="Setting line position in an edit-box uicontrol">Setting line position in an edit-box uicontrol </a> <small>Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/xlswrite-for-mac-linux/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>Controlling callback re-entrancy</title>
		<link>https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=controlling-callback-re-entrancy</link>
					<comments>https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Aug 2011 18:00:57 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2403</guid>

					<description><![CDATA[<p>Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy">Controlling callback re-entrancy</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/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/continuous-slider-callback" rel="bookmark" title="Continuous slider callback">Continuous slider callback </a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I&#8217;d like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King&#8217;s College London. Malcolm is well known in the Matlab-Java community for his <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15580-using-java-swing-components-in-matlab">jcontrol utility</a>. Some months ago, I mentioned his work on another File Exchange contribution, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilities">MUtilities</a> when I discussed <a target="_blank" href="/articles/transparent-matlab-figure-window/">transparent Matlab figure windows</a>. Today, Malcolm discusses one of his lesser-known but extremely important <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">isMultipleCall utility</a>.</i><br />
Every now and again, a very simple bit of code turns out to be more useful than the author initially imagined. Something I have repeatedly used is the <i><b>isMultipleCall</b></i> function which I <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">posted</a> to MATLAB Central&#8217;s File Exchange a year or so ago.<br />
The <i><b>isMultipleCall</b></i> function uses fully-documented pure-MATLAB to extend the control that can be achieved over callbacks.<br />
Here was the problem: I had a modular system built in MATLAB which allowed third-party developers to add their own plugins. I wanted a mechanism to force the dismissal (&#8220;bail-out&#8221;) of a callback even when the <b>Interruptible</b> property of the parent object was set to &#8216;on&#8217;. Such callback re-entrancy issues are common for rapidly-firing events, and debugging and fixing them is usually <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/5809-how-to-implement-a-speed-limit-for-gui-button-press">not easy</a>.<br />
The callback&#8217;s dismissal code would need to be fast because it might be called many dozens of times, e.g. in a <b>WindowButtonMotion</b> callback. An obvious approach was to check the function call stack using MATLAB&#8217;s <i><b>dbstack</b></i> function. Although, at first, this seemed likely to be too slow, profiling showed it was not – taking &lt; 40&micro;sec per call &#8211; and within a <b>WindowButtonMotion</b> callback in a real GUI, I could not perceive any slowing of the code.<br />
Here is the function:</p>
<pre lang='matlab'>
function flag=isMultipleCall()
  flag = false;
  % Get the stack
  s = dbstack();
  if numel(s)< =2
    % Stack too short for a multiple call
    return
  end
  % How many calls to the calling function are in the stack?
  names = {s(:).name};
  TF = strcmp(s(2).name,names);
  count = sum(TF);
  if count>1
    % More than 1
    flag = true;
  end
end
</pre>
<p>With <i><b>isMultipleCall</b></i> invoked from another function (see note below), <i><b>dbstack</b></i> will return a structure with a minimum of 2 elements – the first relating to <i><b>isMultipleCall</b></i> itself and the second to the calling function. So with <i><b>numel</b></i>(s) &lt;= 2, there can be no multiple calls and we can return false immediately thus saving time in doing any further testing.  For <i><b>numel</b></i>(s) &gt; 2 we simply check to see whether the calling functions referenced in s(2) appears anywhere else on the stack. If it does, then we return true; otherwise false.<br />
Then, in our callback code we simply use:</p>
<pre lang='matlab'>if isMultipleCall();  return;  end</pre>
<p>If this line is placed first in the callback function code, it essentially mimics the behavior that you might expect after setting the <b>Interruptible</b> property of the event firing object to &#8216;off&#8217;. Adding a <i><b>drawnow()</b></i> at the end of the callback will ensure that any waiting callbacks in the queue are dismissed:</p>
<pre lang='matlab'>
function MyCallback(hObj, EventData)
  % Quick bail-out if callback code is called before another has ended
  if isMultipleCall();  return;  end
  ...  % do some actual callback work here
  drawnow();
end
</pre>
<p>There are several ways in which <i><b>isMultipleCall</b></i> can extend the standard MALAB functionality. First, by moving <i><b>isMultipleCall</b></i> reference from the first line of the callback we can create both an interruptible and an uninteruptible code block, e.g.</p>
<pre lang='matlab'>
function MyCallback(hObj, EventData)
  %Code Block 1
  ...
  if isMultipleCall();  return;  end
  %Code Block 2
  ...
  drawnow();
end
</pre>
<p>Second, as <i><b>isMultipleCall</b></i> controls the callbacks  &#8211; not the objects that trigger them &#8211; we can individually control the callbacks of objects which fire multiple events. That is particularly useful with Java components, which gives a third extension – <i><b>isMultipleCall</b></i> can be used in any function: not just the callbacks of standard MATLAB components, but also of Java or COM components.<br />
 <br />
Finally, as the callback, not the object is being controlled, we can control a callback that may be shared between multiple objects e.g. a menu component and a toolbar button.<br />
Not bad for 13 lines of code.<br />
Note: <i><b>isMultipleCall</b></i> must be called from a function, not from a string in the callback property.<br />
Do you have any other favorite mechanism for controlling callback re-entrancy? If so, please <a href="/articles/controlling-callback-re-entrancy/#respond">post a comment</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy">Controlling callback re-entrancy</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/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/continuous-slider-callback" rel="bookmark" title="Continuous slider callback">Continuous slider callback </a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy/feed</wfw:commentRss>
			<slash:comments>17</slash:comments>
		
		
			</item>
		<item>
		<title>Running VB code in Matlab</title>
		<link>https://undocumentedmatlab.com/articles/running-vb-code-in-matlab?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-vb-code-in-matlab</link>
					<comments>https://undocumentedmatlab.com/articles/running-vb-code-in-matlab#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 20 Jul 2011 19:36:05 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[ActiveX]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2174</guid>

					<description><![CDATA[<p>Matlab does not natively enable running VB code, but a nice trick enables us to do just that</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/running-vb-code-in-matlab">Running VB code in Matlab</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/runtime-code-instrumentation" rel="bookmark" title="Runtime code instrumentation">Runtime code instrumentation </a> <small>Conditional breakpoints can be used to instrument code with user-specified code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output" rel="bookmark" title="Parsing mlint (Code Analyzer) output">Parsing mlint (Code Analyzer) output </a> <small>The Matlab Code Analyzer (mlint) has a lot of undocumented functionality just waiting to be used. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-memory-leaks-performance" rel="bookmark" title="Matlab-Java memory leaks, performance">Matlab-Java memory leaks, performance </a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab has a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/bp_kqh7.html">variety of interfaces</a> to external programming languages. We can easily access ActiveX and COM-enabled applications from Matlab. Matlab also provides easy access to most COM/ActiveX functionalities, with a few exceptions and limitations.<br />
Unfortunately, Microsoft&#8217;s VBScript is not one of the supported interface languages in Matlab. Therefore, if we need to use VBScript to customize ActiveX or COM functionality or appearance, we have a problem. In some cases, the ActiveX/COM application provides internal methods or properties that enables us to bypass the need for direct VBScript. But in other cases, VBScript is unavoidable.<br />
Today I&#8217;ll show one such example, and how we can run the required VBScript code in Matlab. Note that the entire discussion is Microsoft oriented, and therefore only applicable to Microsoft Windows. And yes &#8211; not a single word today about Java&#8230;</p>
<h3 id="need">The need</h3>
<p>One of the standard controls in Microsoft Windows is ListViewCtrl (more precisely, <code>MSComctlLib.ListViewCtrl.2</code>), which provides a simple sortable table ActiveX. ListViewCtrl should be available on practically all Windows installations, in \Windows\System32\MSCOMCTL.OCX. It is an ancient control (over a decade old), yet still widely used in the ActiveX world.<br />
While Matlab includes a built-in <i><b>uitable</b></i> function, it is sometimes beneficial to use ListViewCtrl instead. For example, ListViewCtrl enables easy setting of cell-specific tool-tips (ok, yes, this can also be done in <i><b>uitable</b></i>s but it&#8217;s not as easy as in ListViewCtrl). ListViewCtrl also enables easy setting of row color and <a target="_blank" rel="nofollow" href="http://www.foxite.com/articles/read.aspx?id=39&#038;document=taming-the-microsoft-listview-control">other goodies</a>.<br />
So ok &#8211; all of these can be overcome in <i><b>uitable</b></i> which is cross-platform (not just Windows-specific) and has some very important features missing from ListViewCtrl (perhaps most importantly, <i><b>uitable</b></i> doesn&#8217;t <b>look</b> a decade old, as ListViewCtrl does). Still, when maintaining legacy code you sometimes don&#8217;t have the luxury of using modern controls.<br />
Indeed, I once needed to use ListViewCtrl, when I ran into today&#8217;s issue. Here&#8217;s a simple usage example:</p>
<pre lang="matlab">
% Set the control's position to be just inside
% the container's pixel position
initPos = getpixelposition(hParent) + [2,3,-5,-5];
[hActiveX,hContainer] = actxcontrol('MSComctlLib.ListViewCtrl.2', ...
                                    initPos, gcf, ...
                                    @lbEventHandler);
bgColor = get(hContainer,'backgroundColor');
bgColorDec = sum(floor(bgColor*256).*(256.^[0:2]));  %#ok
% Customize the control's appearance
set(hActiveX, 'view','lvwReport', 'BorderStyle','ccNone', ...
              'AllowColumnReorder',0, 'Appearance','ccFlat', ...
              'Sorted',0, 'Checkboxes',1, 'FullRowSelect',1, ...
              'HotTracking',1, 'HoverSelection',0, ...
              'HideColumnHeaders',0, 'BackColor',bgColorDec);
% Set the column headers
panelPos = hgconvertunits(gcf, ...
                          get(hContainer,'Position'), ...
                          get(hContainer,'Units'), ...
                          'centimeters', hParent);
panelWidth = panelPos(3)*955;  % [Microsoft units...]
colWidths = panelWidth * [0.2,0.2,0.6];
hColHeaders = get(hActiveX,'ColumnHeaders');
hColHeaders.Add(1,'Name','Name',colWidths(1));
hColHeaders.Add(2,'Type','Type',colWidths(2));
hColHeaders.Add(3,'Comment','Comment',colWidths(3));
% Add some data
blue = hex2dec('FF0000');  % reverse HTML hex color: BBGGRR
data = { 'Orange', 'Fruit',     'My favorite fruit'; ...
         'Onion',  'Vegetable', 'An onion a day keeps everybody else away'; ...
         'Apple',  'Fruit',     'An apple a day keeps the doctor away'; ...
         'Tomato', 'Vegetable', 'You say tomato, I say tomato, let''s call the whole thing off'};
for rowData = data'
    row = hActiveX.ListItems.Add([],rowData{1},rowData{1});
    row.ListSubItems.Add([],[],rowData{2},[],rowData{2});
    row.ListSubItems.Add([],[],rowData{3},[],rowData{3});
    row.ListSubItems.Item(1).ForeColor = blue;
end
</pre>
<p><center><figure style="width: 445px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Unsorted ListViewCtrl" src="https://undocumentedmatlab.com/images/ListViewCtrl_unsorted.png" title="Unsorted ListViewCtrl" width="445" height="172" /><figcaption class="wp-caption-text">Unsorted ListViewCtrl</figcaption></figure></center><br />
While most of ListViewCtrl&#8217;s features are accessible as internal properties and methods, one particular aspect requires VBScript. Which finally brings us to today&#8217;s topic:<br />
Apparently, ListViewCtrl supports data sorting by simply clicking the column headers. Unfortunately, the sort icons (up/down arrows) have to be specified using an <a target="_blank" rel="nofollow" href="http://support.microsoft.com/kb/170146">ImageListCtrl</a> (<code>MSComctlLib.ImageListCtrl.2</code>) that holds the images. ImageListCtrl in turn <a target="_blank" rel="nofollow" href="http://support.microsoft.com/kb/166937">requires</a> using the internal built-in VB function <i>LoadPicture()</i> to load the images.<br />
Unfortunately, Matlab does not enable direct invocation of VB code. So unless we find a way of calling VB&#8217;s internal <i>LoadPicture()</i> directly from Matlab, we cannot use sorting icons in our ListViewCtrl.</p>
<h3 id="ugly">An ugly workaround</h3>
<p>An ugly workaround for this problem is to modify the column name in run-time, so that clicking a column header (e.g., &#8220;Name&#8221;) will sort its data and also modify the column name to &#8220;Name ^&#8221; or &#8220;Name v&#8221;, depending on the sorting order:</p>
<pre lang="matlab">
% Event handler for ListBox item click
% Note: see documentation within %matlabroot%\toolbox\matlab\winfun\private\comeventcallback.m
function lbEventHandler(obj,eventId,item,eventArgs,eventName,varargin)
  try
    if (nargin<5) || ~ischar(eventName)
      return;   % can't tell which event this is
    end
    switch eventName
      case 'ItemClick',
        item.Checked = 1 - item.Checked;
        doSomethingUseful(item);
      case 'ItemCheck',
        % do nothing
      case 'ColumnClick',
        % Update the sorting order for the new (clicked) column
        obj.Sorted = 1;
        newSortKey = item.Index - 1;
        if strcmpi(obj.SortOrder,'lvwAscending') &#038;&#038; (newSortKey == obj.SortKey)
          obj.SortOrder = 'lvwDescending';
          sortStr = ' v';
        else
          obj.SortOrder = 'lvwAscending';
          sortStr = ' ^';
        end
        % Update the column header text with the sort "icon" string
        if (obj.SortKey ~= newSortKey)
          oldColHeader = obj.ColumnHeaders.Item(obj.SortKey + 1);
          oldColHeader.Text = strrep(oldColHeader.Text,' v','');
          oldColHeader.Text = strrep(oldColHeader.Text,' ^','');
          newColHeader = obj.ColumnHeaders.Item(newSortKey + 1);
          newColHeader.Text = [newColHeader.Text sortStr];
        end
        obj.SortKey = newSortKey;
      otherwise,
        % do nothing
    end  % switch eventName
  catch
    handleError;
  end
end  % lbEventHandler
</pre>
<p>As can be seen, the result does not look very professional:<br />
<center><figure style="width: 445px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Sorted ListViewCtrl (ugly)" src="https://undocumentedmatlab.com/images/ListViewCtrl_sorted1.png" title="Sorted ListViewCtrl (ugly)" width="445" height="175" /><figcaption class="wp-caption-text">Sorted ListViewCtrl (ugly)</figcaption></figure></center></p>
<h3 id="solution">The solution</h3>
<p>The solution to the problem is to use a not-well-known COM server component called <a target="_blank" rel="nofollow" href="http://support.microsoft.com/kb/184740">ScriptControl</a> (<code>MSScriptControl.ScriptControl</code>). By using ScriptControl's <i>eval()</i> function we can call the built-in <loadpicture ()</i> function and everybody's happy:</p>
<pre lang="matlab">
% Load the images using ScriptControl
hScriptControl = actxserver('MSScriptControl.ScriptControl');
hScriptControl.Language = 'VBScript';
picUp   = hScriptControl.Eval('LoadPicture("..\Icons\UpIcon.gif")');
picDown = hScriptControl.Eval('LoadPicture("..\Icons\DownIcon.gif")');
% Now prepare an ImageList with these images
[hImageListActiveX, hContainer2] = actxcontrol('MSComctlLib.ImageListCtrl.2',initPos);
set(hContainer2,'Pos',[initPos(1:2),1,1]);  % hide the control
hImageListActiveX.ListImages.Add([],[],picUp);
hImageListActiveX.ListImages.Add([],[],picDown);
% Finally, attach the images to the ListViewCtrl headers
hActiveX.ColumnHeaderIcons = hImageListActiveX;
</pre>
<p>And now modify the sorting icon whenever a column header is clicked:</p>
<pre lang="matlab">
% Event handler for ListBox item click
% Note: see documentation within %ML\toolboc\matlab\winfun\private\comeventcallback.m
function lbEventHandler(obj,eventId,item,eventArgs,eventName,varargin)
  try
    if (nargin<5) || ~ischar(eventName)
      return;   % can't tell which event this is
    end
    switch eventName
      case 'ItemClick',
        item.Checked = 1 - item.Checked;
        doSomethingUseful(item);
      case 'ItemCheck',
        % do nothing
      case 'ColumnClick',
        % Update the sorting order for the new (clicked) column
        obj.Sorted = 1;
        newSortKey = item.Index - 1;
        if strcmpi(obj.SortOrder,'lvwAscending') &#038;&#038; (newSortKey == obj.SortKey)
          obj.SortOrder = 'lvwDescending';
          sortIconIndex = 1;
        else
          obj.SortOrder = 'lvwAscending';
          sortIconIndex = 0;
        end
        % Remove sort icon from previous column
        setSortIcon(obj.hWnd,obj.SortKey,-1);
        % Add the sort icon to the clicked column header
        setSortIcon(obj.hWnd,newSortKey,sortIconIndex);
        % Update the previous column header text, to remove '...' due to the sort icon
        if (obj.SortKey ~= newSortKey)
          oldColHeader = obj.ColumnHeaders.Item(obj.SortKey + 1);
          oldColHeader.Text = oldColHeader.Text;
        end
        obj.SortKey = newSortKey;
      otherwise,
        % do nothing
    end  % switch eventName
  catch
    handleError;
  end
end  % lbEventHandler
</pre>
<p><center><figure style="width: 445px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Sorted ListViewCtrl (much better)" src="https://undocumentedmatlab.com/images/ListViewCtrl_sorted2.png" title="Sorted ListViewCtrl (much better)" width="445" height="174" /><figcaption class="wp-caption-text">Sorted ListViewCtrl (much better)</figcaption></figure></center><br />
This code uses the MEX utility <a target="_blank" href="/files/setSortIcon.zip">setSortIcon</a>, which was developed (not by me, I can't remember by whom) based on <a target="_blank" rel="nofollow" href="http://vbnet.mvps.org/index.html?code/comctl/lvheaderimage.htm">this</a>. Simply unzip the setSortIcon.zip file into your favorite folder on the Matlab path. The zip file contains the c source code, that you can modify and mex-recompile if you wish.</p>
<h3 id="Macros">Running VBA Macros</h3>
<p>A related issue is running VBA macros from Matlab. This was very recently asked and <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/243292#845753">answered</a> on the CSSM forum, so I'll just provide Peter Lorin Rasmussen's code (read higher up in that CSSM thread for more details):</p>
<pre lang='matlab'>
% Initiate active X component
powerPoint = actxserver('PowerPoint.Application');
% Visible
powerPoint.Visible=1;
% Minimize powerpoint
powerPoint.WindowState=2;
% Load presentations object
presentations = powerPoint.presentations;
% Open file
presentation = invoke(presentations,'open',fileName);
% Load VBA project
k = presentation.VBProject.Collection.get();
% Run Macro
k = invoke(presentation.application,'run',macroName,varargin{:});
% Close all
presentation.Save;
presentation.Close;
powerPoint.Quit;
powerPoint.delete;
</pre>
<p>Do you have any favorite code in another programming language that you run from Matlab? Don't be shy - please tell us all about it in a comment <a href="/articles/running-vb-code-in-matlab/#respond">below</a>.</loadpicture></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/running-vb-code-in-matlab">Running VB code in Matlab</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/runtime-code-instrumentation" rel="bookmark" title="Runtime code instrumentation">Runtime code instrumentation </a> <small>Conditional breakpoints can be used to instrument code with user-specified code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output" rel="bookmark" title="Parsing mlint (Code Analyzer) output">Parsing mlint (Code Analyzer) output </a> <small>The Matlab Code Analyzer (mlint) has a lot of undocumented functionality just waiting to be used. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-memory-leaks-performance" rel="bookmark" title="Matlab-Java memory leaks, performance">Matlab-Java memory leaks, performance </a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/running-vb-code-in-matlab/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>COM/ActiveX tips &#038; tricks</title>
		<link>https://undocumentedmatlab.com/articles/com-activex-tips?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=com-activex-tips</link>
					<comments>https://undocumentedmatlab.com/articles/com-activex-tips#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 28 Jul 2010 08:43:26 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[ActiveX]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1781</guid>

					<description><![CDATA[<p>This article describes several little-known tips useful for COM / ActiveX programming in Matlab</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/com-activex-tips">COM/ActiveX tips &amp; tricks</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/some-performance-tuning-tips" rel="bookmark" title="Some Matlab performance-tuning tips">Some Matlab performance-tuning tips </a> <small>Matlab can be made to run much faster using some simple optimization techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance" rel="bookmark" title="Tips for accelerating Matlab performance">Tips for accelerating Matlab performance </a> <small>My article on "Tips for Accelerating MATLAB Performance" was recently featured in the September 2017 Matlab newsletter digest. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab&#8217;s <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Component_Object_Model">COM</a>/<a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/ActiveX">ActiveX</a> interface has been supported and <a target="_blank" rel="nofollow" href="https://www.mathworks.com/help/matlab/ref/com.html">well-documented</a> for many releases. However, there are still some aspects that are either not detailed, or that escape the casual documentation reader.</p>
<h3 id="Collections">Accessing collection items</h3>
<p>COM <i>collections</i> is a COM interface for sets of similar objects such as the worksheets in an Excel file or the images in a PowerPoint document. The items in a collection can be accessed using a numeric index (starting at 1) or the item&#8217;s string name.<br />
The &#8220;normal&#8221; way to access collection items is using the <i>Item()</i> method that accepts a numeric index or the item&#8217;s name (a string).<br />
Since collections are so common, Microsoft devised a short-cut of passing the parameter directly to the collection. For example, in our Excel VB code, instead of using <i>Worksheets.Item(2)</i> or <i>Worksheets.Item(&#8216;Sheet2&#8217;)</i>, we could write <i>Worksheets(2)</i> or <i>Worksheets(&#8216;Sheet2&#8217;)</i>. This shortcut is so common that the &#8220;normal&#8221; way of using <i>Item()</i> is rarely seen.<br />
Unfortunately, Matlab&#8217;s implementation of the COM interface does not recognize this shortcut. Instead, we must use the more verbose way of using the <i>Item()</i>:</p>
<pre lang="matlab">
% Invalid - shortcut is not recognized by Matlab
>> hSheet = hWorkbook.Worksheets(2);
??? Index exceeds matrix dimensions
% Valid
>> hSheet = hWorkbook.Worksheets.Item(2);
>> hSheet = hWorkbook.Worksheets.Item('Sheet2')
hSheet =
	Interface.Interface.Microsoft_Excel_11.0_Object_Library._Worksheet
</pre>
<p>Note that the dot-notation used above only works on recent Matlab 7 releases. Earlier releases (for example, Matlab 6.0 R12) have bugs that prevent it from functioning properly. The workaround is to use the following even-more-verbose way, which work on all Matlab releases:</p>
<pre lang="matlab">hSheet = invoke(get(hWorkbook,'Worksheets'),'Item',2);</pre>
<p>Matlab&#8217;s documentation actually has a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f27433.html#f27442">short section</a> describing the valid way to access COM collection. IMHO, a special warning about the invalid but widely-used short-cut would have been useful. In any case, the issue of accessing collection items has often appeared on CSSM (for example, <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/286930">here</a> and <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/286988">here</a>), so I guess many programmers have overlooked this.</p>
<h3 id="Enumerations">Using enumerated values</h3>
<p>When setting COM property values, Matlab supports some enumerated (constant) values but not all (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f89715.html#f107980">read here</a>). In practice, this can be very frustrating since the VB code and documentation almost always refers to the enumerated values only. Without the ability to set enumeration values, some properties become unusable in Matlab.<br />
Well, not really. There&#8217;s a workaround: Since every enumerated COM value hides a numeric value, we can pass the numeric values rather than the enumerated (string) value when setting such properties. The numeric values are seldom documented, but can often be easily found online (use Google!). Quite often, they appear in C header-files that #define the enumerated values as pre-processor items with the required numeric value. For example, the numeric value for xlXYScatterLines is <a target="_blank" rel="nofollow" href="http://www.google.com/search?q=%22define+xlXYScatterLines%22">easily found</a> to be 74.<br />
Some of the enumerated constants are harder to find in this manner. You can use one of the following resources to search for your requested constant: <a target="_blank" rel="nofollow" href="http://techsupt.winbatch.com/ts/T000001033005F9.html">Excel</a>, <a target="_blank" rel="nofollow" href="http://www.wizardwrx.com/CommonTypelibs/O2000_MSPPT9.CSV">PowerPoint</a> (or <a target="_blank" rel="nofollow" href="http://techsupt.winbatch.com/webcgi/webbatch.exe?techsupt/nftechsupt.web+WinBatch/OLE~COM~ADO~CDO~ADSI~LDAP/Constants+PPCONST.txt">here</a>), <a target="_blank" rel="nofollow" href="http://techsupt.winbatch.com/ts/T000001033F49.html">OLE/Office</a> (includes Word, Access and Internet Explorer), and an <a target="_blank" rel="nofollow" href="http://techsupt.winbatch.com/webcgi/webbatch.exe?techsupt/nftechsupt.web+WinBatch/OLE~COM~ADO~CDO~ADSI~LDAP//Constants">even larger list</a>.<br />
Again, old Matlab versions have problems understanding string enumerations, but the numeric values are always accepted and so are backward-compatible. If your application needs to support old Matlab versions, always use the numeric values (add a comment with the enumerated name, for maintainability).</p>
<h3 id="Office2010">Office 2010</h3>
<p>Microsoft Office 2010 has apparently changed its COM interface, so accessing it from Matlab cannot easily be done. Luckily, Samuel Foucher has posted a workaround to this problem <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/287717#766303">on CSSM yesterday</a>. The trick is basically to have both an older Office and Office 2010 installed at the same time. As Samuel notes, &#8220;<i>This is far from an optimal solution but it seems to work so far</i>&#8220;. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/com-activex-tips">COM/ActiveX tips &amp; tricks</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/some-performance-tuning-tips" rel="bookmark" title="Some Matlab performance-tuning tips">Some Matlab performance-tuning tips </a> <small>Matlab can be made to run much faster using some simple optimization techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance" rel="bookmark" title="Tips for accelerating Matlab performance">Tips for accelerating Matlab performance </a> <small>My article on "Tips for Accelerating MATLAB Performance" was recently featured in the September 2017 Matlab newsletter digest. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/com-activex-tips/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
	</channel>
</rss>
