<?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>ActiveX &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/activex/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 10 Sep 2014 18:00:55 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>CheckboxList</title>
		<link>https://undocumentedmatlab.com/articles/checkboxlist?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=checkboxlist</link>
					<comments>https://undocumentedmatlab.com/articles/checkboxlist#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Sep 2014 18:00:55 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[ActiveX]]></category>
		<category><![CDATA[Internal component]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5012</guid>

					<description><![CDATA[<p>Matlab listboxes can be enhanced with checkboxes next to each item. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/checkboxlist">CheckboxList</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-layout-customization" rel="bookmark" title="Listbox layout customization">Listbox layout customization </a> <small>Matlab's listbox layout can be modified to display multiple item columns and different inter-cell margins. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-listbox-mouse-actions" rel="bookmark" title="Setting listbox mouse actions">Setting listbox mouse actions </a> <small>Matlab listbox uicontrol can be modified to detect mouse events for right-click context menus, dynamic tooltips etc....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Several years ago I blogged about using a <a target="_blank" href="/articles/customizing-uitree-nodes-2">checkbox-tree in Matlab</a>. A few days ago there was a question on the Matlab Answers forum <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/152364-variable-amount-of-checkboxes-in-listbox-programmatic-gui">asking</a> whether something similar can be done with Matlab listboxes, i.e. add checkboxes next to each list item. There are actually several alternatives for this and I thought this could be a good opportunity to discuss them:</p>
<ul>
<li><a href="/articles/checkboxlist#HTML">The HTML image variant</a></li>
<li><a href="/articles/checkboxlist#TMW">MathWorks CheckBoxList</a></li>
<li><a href="/articles/checkboxlist#JIDE">JIDE&#8217;s CheckBoxList</a></li>
<li><a href="/articles/checkboxlist#ActiveX">ActiveX and other alternatives</a></li>
<li><a href="/articles/checkboxlist#uitable">Matlab <i><b>uitable</b></i> in disguise</a></li>
</ul>
<p><center><figure style="width: 289px" class="wp-caption aligncenter"><img decoding="async" alt="MathWorks CheckBoxList" src="https://undocumentedmatlab.com/images/CheckBoxList.png" title="MathWorks CheckBoxList" width="289" height="171" /><figcaption class="wp-caption-text">MathWorks CheckBoxList</figcaption></figure></center><br />
<span id="more-5012"></span></p>
<h3 id="HTML">The HTML image variant</h3>
<p>The simplest alternative is to use small icon images checked and unchecked as part of the listbox item labels. As I <a target="_blank" href="/articles/rich-contents-log-panel">explained</a> last year, listboxes (like all other Matlab uicontrols that rely on underlying Java Swing components), <a target="_blank" href="/articles/html-support-in-matlab-uicomponents">support HTML</a> and can be formatted using HTML images. For example:<br />
<center><figure style="width: 200px" class="wp-caption aligncenter"><img decoding="async" alt="Matlab listbox with HTML image icons" src="https://undocumentedmatlab.com/images/editbox10.png" title="Matlab listbox with HTML image icons" width="200" height="60" /><figcaption class="wp-caption-text">Matlab listbox with HTML image icons</figcaption></figure></center><br />
In order to check/uncheck items in the listbox, we can trap the underlying Java component&#8217;s <b>MouseClickedCallback</b> using the <a target="_blank" href="/articles/findjobj-find-underlying-java-object">findjobj utility</a>:</p>
<pre lang='matlab'>
% Assume checked.gif, unchecked.gif are 16x16 icons
prefix = ['<html><img decoding="async" src="file:///' strrep(path_of_icon_files),'\','/') '/unchecked.gif" height=16 width=16 />'];
sampleData = strcat(prefix, {'first', 'Second', 'Third', 'and last'});  % all items are unchecked at first
hListbox = uicontrol(...);
jScrollPane = findjobj(hListbox);
jListbox = handle(jScrollPane.getViewport.getView, 'CallbackProperties');
jListbox.MouseClickedCallback = {@mouseClickedFcn,hListbox};
function mouseClickedFcn(jListbox, jEventData, hListbox)
   % Get the clicked item and row index
   clickedX = jEventData.getX;
   clickedY = jEventData.getY;
   if clickedX > 15,  return;  end  % did not click a checkbox so bail out
   clickedRow = jListbox.locationToIndex(java.awt.Point(clickedX,clickedY)) + 1;  % Matlab row index = Java row index+1
   if clickedRow <= 0,  return;  end  % clicked not on an item - bail out
   strs = get(hListbox,'String');
   clickedItem = strs{clickedRow};
   % Switch the icon between checked.gif <=> unchecked.gif
   if strfind(clickedItem,'unchecked')
       strs{clickedRow} = strrep(clickedItem,'unchecked','checked');
   else
       strs{clickedRow} = strrep(clickedItem,'checked','unchecked');
   end
   set(hListbox,'String',strs);  % update the list item
end
</pre>
<p>Finally, when we process the selected list item(s), we can simply check whether they contain &#8216;unchecked.gif&#8217; or &#8216;checked.gif&#8217;. Pretty straight-forward stuff.</p>
<h3 id="TMW">MathWorks CheckBoxList</h3>
<p><code>com.mathworks.mwswing.checkboxlist.CheckBoxList</code> is a <code>JList</code> extension that displays a list of labels in a list with a checkbox next to each label. The labels&#8217; checkboxes can be set, unset and queried using methods supplied by the <code>CheckBoxList</code> class or its <code>com.mathworks.mwswing.checkboxlist.DefaultListCheckModel</code> model:</p>
<pre lang='matlab'>
% First create the data model
jList = java.util.ArrayList;  % any java.util.List will be ok
jList.add(0,'First');
jList.add(1,'Second');
jList.add(2,'Third');
jList.add(3,'and last');
% Next prepare a CheckBoxList component within a scroll-pane
jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(jList);
jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList);
% Now place this scroll-pane within a Matlab container (figure or panel)
[jhScroll,hContainer] = javacomponent(jScrollPane,[10,10,80,65],gcf);
% Update some items' state programmatically
jCBModel = jCBList.getCheckModel;
jCBModel.checkAll;
jCBModel.uncheckIndex(1);
jCBModel.uncheckIndex(3);
% Respond to checkbox update events
jhCBModel = handle(jCBModel, 'CallbackProperties');
set(jhCBModel, 'ValueChangedCallback', @myMatlabCallbackFcn);
</pre>
<p>This results in the following image:<br />
<center><figure style="width: 289px" class="wp-caption aligncenter"><img decoding="async" alt="MathWorks CheckBoxList" src="https://undocumentedmatlab.com/images/CheckBoxList.png" title="MathWorks CheckBoxList" width="289" height="171" /><figcaption class="wp-caption-text">MathWorks CheckBoxList</figcaption></figure></center><br />
We can query the various checked/unchecked states programmatically:</p>
<pre lang='matlab'>
>> jCBList.getCheckedValues
ans =
[First, Third]
>> jCBList.getCheckedIndicies'
ans =
           0       2
>> jCBModel.isIndexChecked(0)
ans =
     1    % =true
</pre>
<h3 id="JIDE">JIDE&#8217;s CheckBoxList</h3>
<p>There is also an unrelated JIDE equivalent: <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/com/jidesoft/swing/CheckBoxList.html"><code>com.jidesoft.swing.CheckBoxList</code></a>. Readers are referred to the JIDE documentation for additional details.<br />
The basic idea is the same as with the MathWorks <code>CheckBoxList</code>: we create the data model, then create a <code>CheckBoxList</code> component within a <code>JScrollPane</code> and place this onscreen using the <a target="_blank" href="/articles/javacomponent"><i><b>javacomponent</b></i> function</a>. We can then modify or query the data model programmatically, and set various callback functions to process user events.</p>
<pre lang='matlab'>
% Prepare the data model as above
% Now display onscreen:
jCBList = com.jidesoft.swing.CheckBoxList(jList.toArray)
jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList);
[jhScroll,hContainer] = javacomponent(jScrollPane, [120,10,80,65], gcf);
% Do some programmatic updates:
jCBList.selectAll;  % reverse: jCBList.selectNone
jCBList.setCheckBoxListSelectedIndices([0,2]);
</pre>
<p>The appearance is very similar to the MathWorks <code>CheckBoxList</code>, except that JIDE&#8217;s <code>CheckBoxList</code> has slightly less space between the list rows, and between the checkboxes and labels. The main difference between these components is not in their visual appearance but rather in their supported functionalities (internal methods) &#8211; some people might prefer the MathWorks component, others might like JIDE better. To see these functionalities, use my <a target="_blank" href="/articles/uiinspect">uiinspect</a> and/or <a target="_blank" href="/articles/checkclass">checkClass</a> utilities.<br />
For additional information on the MathWorks and JIDE components, and how to investigate and customize them, see Chapter 5 of my <a target="_blank" href="/matlab-java-book">Matlab-Java programming book</a>.</p>
<h3 id="ActiveX">ActiveX and other alternatives</h3>
<p>If you are running on Windows, you could use ActiveX controls that implement checkbox list functionality. One such control that is pretty standard is Microsoft&#8217;s <code>MSComctlLib.ListViewCtrl.2</code>. I showed an <a target="_blank" href="/articles/running-vb-code-in-matlab">example of ListViewCtrl usage</a> a few years ago, and readers are referred there for details. Here is the end result:<br />
<center><figure style="width: 445px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Sorted ListViewCtrl" src="https://undocumentedmatlab.com/images/ListViewCtrl_sorted2.png" title="Sorted ListViewCtrl" width="445" height="174" /><figcaption class="wp-caption-text">Sorted ListViewCtrl</figcaption></figure></center><br />
Granted, this is more of a table having a checkbox column than a listbox, but you can easily make the <code>ListViewCtrl</code> have only a single column.<br />
In addition to this standard <code>ListViewCtrl</code> control, there are plenty of other third-party ActiveX or Java controls that can more-or-less easily be integrated in our Matlab GUI. The drawback of ActiveX is that it only works on a limited set of platforms, whereas the Java-based components (either MathWorks or JIDE) work on all Matlab installations.</p>
<h3 id="uitable">Matlab <i><b>uitable</b></i> in disguise</h3>
<p>As a variant of the idea of using a table with a checkbox first column, we could use Matlab&#8217;s builtin <i><b>uitable</b></i> function, as <a href="/articles/checkboxlist#comment-331906">suggested by Sebastian below</a>. Here is a simple code snippet illustrating this idea:</p>
<pre lang='matlab'>
data = {true,'First'; false,'Second'; true,'Third'; false,'and last'};
hTable = uitable('Data',data,'RowName',[],'ColumnName',[],'BackgroundColor',[1,1,1],'Position',[10,10,100,70],'ColumnWidth',{20,60});
</pre>
<p><center><figure style="width: 100px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab uitable with checkbox column" src="https://undocumentedmatlab.com/images/checkbox_uitable.gif" title="Matlab uitable with checkbox column" width="100" height="70" /><figcaption class="wp-caption-text">Matlab uitable with checkbox column</figcaption></figure></center><br />
Anyway, let no one say ever again that Matlab GUI is boring. It is not. It is only limited by our imagination and our willingness to find and customize components that implement our requirements. There are plenty of alternatives out there, we just need to reach out and use them. If you can&#8217;t do it yourself, you could always use an external consultant like me to help you.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/checkboxlist">CheckboxList</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-layout-customization" rel="bookmark" title="Listbox layout customization">Listbox layout customization </a> <small>Matlab's listbox layout can be modified to display multiple item columns and different inter-cell margins. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-listbox-mouse-actions" rel="bookmark" title="Setting listbox mouse actions">Setting listbox mouse actions </a> <small>Matlab listbox uicontrol can be modified to detect mouse events for right-click context menus, dynamic tooltips etc....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/checkboxlist/feed</wfw:commentRss>
			<slash:comments>24</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>Waiting for asynchronous events</title>
		<link>https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=waiting-for-asynchronous-events</link>
					<comments>https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 Jul 2012 18:50:57 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[ActiveX]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3017</guid>

					<description><![CDATA[<p>The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events">Waiting for asynchronous events</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/blocked-wait-with-timeout-for-asynchronous-events" rel="bookmark" title="Blocked wait with timeout for asynchronous events">Blocked wait with timeout for asynchronous events </a> <small>It is easy to convert asynchronous (streaming) events into a blocked wait in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>It often happens that we need our program to wait for some condition to occur. This condition may depend on some external process that updates the condition <i>asynchronously</i>, meaning in a non-predictable (non-specific) time. A typical example is user mouse or keyboard actions in a GUI dialog window, or a specific signal that is received from hardware.</p>
<h3 id="waitfor"><i>waitfor</i> and other built-in functions</h3>
<p>Matlab has a couple of built-in functions for blocking Matlab&#8217;s main processing thread until certain asynchronous GUI events occurs. <i><b>waitfor</b></i> is documented to block code execution until either the specified GUI handle object is deleted, or is updated (possibly to a specified value), or Ctrl-C is pressed in matlab&#8217;s Command Window. <i><b>uiwait</b></i> similarly blocks execution, until a specified figure handle is deleted/closed, or a separate processing thread (typically, a callback function) calls the corresponding <i><b>uiresume</b></i> (I <a target="_blank" href="/articles/disable-entire-figure-window/">discussed</a> <i><b>uiwait/uiresume</b></i>, together with their <i><b>uisuspend/uirestore</b></i> siblings, last year). <i><b>uiwait</b></i>, unlike <i><b>waitfor</b></i>, has an optional timeout parameter; on the other hand, <i><b>uiwait</b></i> cannot wait for a non-deletion event on a regular <i><b>uicontrol</b></i> property, as <i><b>waitfor</b></i> can.<br />
Other related built-in Matlab functions are <i><b>waitforbuttonpress, pause</b></i> (which awaits user mouse/keyboard clicks), and <i><b>ginput, gtext, rbbox, dragrect</b></i> (which awaits mouse clicks in a plot/image axes). Some toolboxes have other similar blocking functions, for example <i><b>roipoly</b></i> in the Image Processing toolbox.</p>
<h3 id="Non-HG">Waiting for events on non-HG objects</h3>
<p>But what if we need to wait for an event to happen on a non-Matlab (HG) object? Say on an ActiveX control property or even on a non-graphical Java object?<br />
It turns out that <i><b>waitfor</b></i> can also be used in these cases. Although not documented, <i><b>waitfor</b></i> actually accepts handles not only of HG objects (e.g., figure handles) but also of other types of handles, such as regular Java reference handles. The usage is the same as for regular HG handles:</p>
<pre lang='matlab'>waitfor(objectHandleOrReference, 'propertyName', propertyValue);</pre>
<p>For example, to wait for data to be available in a <code>java.util.Hashtable</code> object, which has a public boolean <i>isEmpty()</i> method and therefore returns a value of &#8216;on&#8217; or &#8216;off&#8217; for <i><b>get</b>(object,&#8217;Empty&#8217;)</i>:</p>
<pre lang='matlab'>waitfor(javaHashTableReference, 'Empty', 'off');</pre>
<p><span id="more-3017"></span><br />
(Note that Matlab automatically converts a Java <code>boolean</code> into &#8216;on&#8217;/&#8217;off&#8217; in such cases, so we need to use &#8216;on&#8217;/&#8217;off&#8217; rather than true/false; this is not always the case &#8211; a counter-case is presented immediately below)</p>
<h3 id="timeout">Setting a timeout on <i>waitfor</i></h3>
<p>To set a timeout on our blocked wait, a feature of <i><b>uiwait</b></i> that is missing in the built-in <i><b>waitfor</b></i>, we can use a dedicated one-time timer object. Timer callbacks use a separate thread from the main Matlab processing thread, and are therefore processed even when the Main thread is blocked. The implementation is quite easy, as shown below:</p>
<pre lang='matlab'>
% Wait for data updates to complete (isDone = false if timeout, true if data ok)
function isDone = waitForDone(object,timeout)
    % Initialize: timeout flag = false
    object.setDone(false);
    % Create and start the separate timeout timer thread
    hTimer = timer('TimerFcn',@(h,e)object.setDone(true), 'StartDelay',timeout);
    start(hTimer);
    % Wait for the object property to change or for timeout, whichever comes first
    waitfor(object,'Done',true);
    % waitfor is over - either because of timeout or because the data changed
    % To determine which, check whether the timer callback was activated
    isDone = (hTimer.TasksExecuted == 0);
    % Delete the time object
    try stop(hTimer);   catch, end
    try delete(hTimer); catch, end
    % Return the flag indicating whether or not timeout was reached
end  % waitForDone
</pre>
<h3 id="Polling">Polling</h3>
<p>In some cases (for example, waiting on a specific field value within a struct, which <i><b>waitfor</b></i> does not support), we need to revert to using plain-ol&#8217; <i>polling</i>, rather than the more efficient blocked wait. In such cases, I strongly advice to place a certain <i><b>pause</b></i> within the polling loop:</p>
<pre lang='matlab'>
delay = 0.01;  % 10 milliseconds
while ~object.isDone  % set by the callback
    pause(delay);  % a slight pause to let all the data gather
end
</pre>
<p>Or, a variant with timeout:</p>
<pre lang='matlab'>
delay = 0.01;
for idx = 1 : (timeout/delay)  % wait up to N secs before giving up
    if object.isDone  % set by the callback
        break;
    end
    pause(delay);  % a slight pause to let all the data gather
end
</pre>
<p>The reason we need this deliberate <i><b>pause</b></i> is to enable the CPU to process other processing threads, namely that thread which is responsible for updating the field value in due time. Without this <i><b>pause</b></i>, it would take the CPU much longer (if at all) to get to that thread, and our overall application performance will actually <u>degrade</u>, since the event will take longer to get processed.<br />
Adding deliberate <i><b>pause</b></i> delays as a mechanism to improve overall performance may sound counter-intuitive, but this is in fact the case here. Performance tuning can indeed be counter-intuitive sometimes, until you learn the underlying reasons when it becomes clear (I&#8217;ve shown several examples of this in the past, <a target="_blank" href="/articles/matrix-processing-performance/">here</a>, <a target="_blank" href="/articles/matlab-java-memory-leaks-performance/">here</a>, <a target="_blank" href="/articles/cellfun-undocumented-performance-boost/">here</a> and <a target="_blank" href="/articles/performance-scatter-vs-line/">here</a>).<br />
We should take care not to set too high a <i><b>pause</b></i> delay, since that will unnecessarily delay processing of the incoming event; on the other hand, setting it too low will return the thread-starvation issue explained above. A <i><b>pause</b></i> value of 5-50 millisecs (0.005-0.05) should be about right for the vast majority of applications. Note that different platforms run your application at different speeds, so be careful not to over-tune this delay to a particular computer.<br />
Interested in learning more Matlab performance or advanced programming tricks? Then consider joining my <a target="_blank" href="/courses/Matlab_Performance_Tuning_Course.pdf">Matlab Performance Tuning</a>, <a target="_blank" href="/courses/Advanced_Matlab_GUI_Course_1d.pdf">Advanced Matlab GUI</a> and/or <a target="_blank" href="/courses/Using_Java_in_Matlab_Course.pdf">Matlab-Java programming</a> seminars in Geneva on August 21-23, 2012 – <a href="mailto:%20altmany%20@gmail.com?subject=Matlab%20courses&amp;body=Hi%20Yair,%20&amp;cc=;&amp;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab seminars&amp;body=Hi Yair, '); return false;">email me</a> (altmany at gmail dot com) for details. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events">Waiting for asynchronous events</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/blocked-wait-with-timeout-for-asynchronous-events" rel="bookmark" title="Blocked wait with timeout for asynchronous events">Blocked wait with timeout for asynchronous events </a> <small>It is easy to convert asynchronous (streaming) events into a blocked wait in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events/feed</wfw:commentRss>
			<slash:comments>33</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>
