<?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>Robert Cumming &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/robert-cumming/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 08 Jul 2015 18:00:30 +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>Capturing print events</title>
		<link>https://undocumentedmatlab.com/articles/capturing-print-events?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=capturing-print-events</link>
					<comments>https://undocumentedmatlab.com/articles/capturing-print-events#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 08 Jul 2015 18:00:30 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Robert Cumming]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5909</guid>

					<description><![CDATA[<p>Matlab print events can be trapped by users to enable easy printout customization. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/capturing-print-events">Capturing print 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/customizing-print-setup" rel="bookmark" title="Customizing print setup">Customizing print setup </a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/detecting-window-focus-events" rel="bookmark" title="Detecting window focus events">Detecting window focus events </a> <small>Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....</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>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events" rel="bookmark" title="Matlab callbacks for uifigure JavaScript events">Matlab callbacks for uifigure JavaScript events </a> <small>Matlab callback code can be attached to JavaScript events in web-based uifigures. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>As a followup to my recent post on capturing and using <a target="_blank" href="/articles/undocumented-hg2-graphics-events">HG2&#8217;s new graphic events</a>, I would like to welcome back guest blogger Robert Cumming, who developed a commercial <a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework">Matlab GUI framework</a>. Today, Robert will highlight an unusual use of event listeners to enable print output customizations by tapping into print-related events.</i><br />
One of my toolbox clients wanted to ensure that every print-out, of any Matlab GUI, would contain a datestamp footer and a project id header.<br />
Initially I thought this would be a simple task, since the GUI framework already has <i>saveAs</i> and <i>copyToClipboard</i> methods that users could utilize. Moreover, as Yair <a target="_blank" href="/articles/modifying-default-toolbar-menubar-actions">has shown</a> some years ago, we can easily adapt the standard callbacks associated with the Matlab figure toolbar&#8217;s &lt;Print&gt; button and the menu-bar&#8217;s Print action. We can even <a target="_blank" href="/articles/customizing-print-setup">customize the standard print setup</a>. However, all this does not help when directly invoking printout commands from the Matlab command line or from within the user program, for example:</p>
<pre lang='matlab'>
% Create the GUI
[x,y,z] = peaks(75);
surf(x,y,z);
% printout via print() or export_fig
print(gcf, .... )
export_fig filename  % see https://undocumentedmatlab.com/articles/export_fig
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Printout with the expected header and footer stamps" src="https://undocumentedmatlab.com/images/printout_450x383.jpg" title="Printout with the expected header and footer stamps" width="450" height="383" /><figcaption class="wp-caption-text">Printout with the expected header and footer stamps</figcaption></figure></center><br />
<span id="more-5909"></span><br />
This initially posed a bit of a challenge – how could I capture the <i><b>print</b></i> event?<br />
The key to solving this was using events in a different way. Rather than listen for a <i><b>print</b></i> event, we listen for something that <i><b>print</b></i> interacts with in the figure window. This will solve the problem for both <i><b>print</b></i> and <i><b>export_fig</b></i>, since <i><b>export_fig</b></i> uses <i><b>print</b></i> internally.<br />
We can listen to <i><b>get</b></i> and <i><b>set</b></i> events on many Matlab properties. In this instance we can trap <i><b>get</b></i> events on a figure&#8217;s <b>PaperPositioMode</b>, or <b>PaperSize</b> property. <i><b>print</b></i>, <i><b>saveas</b></i> and <i><b>export_fig</b></i> all access these properties before doing the actual printing, so by trapping the event we can run our own function before the printing is done. For example:</p>
<pre lang='matlab'>
classdef PrintListenerDemo
  properties
    referenceNo = 'R1234-56'
  end
  methods (Access=public)
    function obj = PrintListenerDemo
      hFig = figure;
      [x,y,z] = peaks(75);
      surf ( x, y, z );
      % add listener on event to prepare the figure for printing
      addlistener ( hFig, 'PaperPositionMode', 'PreGet', @obj.Prep );
      % Testing only:
      evalin ( 'base', 'print ( gcf, ''-dmeta'' )' );  % simulate user action in command-line
      print(hFig,'-dmeta');    % simulate programmatic printout
    end
    function Prep(obj, hFig, varargin)
      disp ( 'running function in preparation for printing.' );
      % Add datestamp and reference id UIControls
      str = sprintf ( 'Printed @ %s', datestr(now) );
      uicontrol ( 'parent',hFig, 'style','text', 'units','normalized', ...
                  'position',[0 0 1 0.07], 'string',str, 'BackgroundColor','white' );
    end
  end
end
</pre>
<p>When we run the above we can see that the <i><b>disp</b></i> message is displayed twice, because the property has two <i><b>get</b></i> calls in the print function. We can easily solve this by saving a temp variable that is created the first time it is run.<br />
The next thing we need to do is to clean up afterwards, i.e. remove the uicontrols and reset the temp variable to ensure that any future print events are captured.<br />
Here you might think the second get call I mentioned above was post printing, but it&#8217;s not.  So we need to capture another event to do the cleaning up.<br />
In this instance I thought about what was likely to happen &#8211; some sort of user interaction, e.g. a mouse move, press or key press. So we can listen for any of those events and run our clean up method. This is shown in the full code below:</p>
<pre lang='matlab'>
% PrintListenerDemo - Demo of print listener methodology
classdef PrintListenerDemo
  properties
    referenceNo = 'R1234-56'
  end
  methods (Access=public)
    function obj = PrintListenerDemo
      hFig = figure;
      [x,y,z] = peaks(75);
      surf ( x, y, z );
      % add listener on event to prepare the figure for printing
      addlistener ( hFig, 'PaperPositionMode', 'PreGet', @obj.Prep );
      % add a few different ways to clean up
      addlistener ( hFig, 'ButtonDown', @obj.CleanUp );
      addlistener ( hFig, 'WindowKeyPress', @obj.CleanUp );
      addlistener ( hFig, 'WindowMouseMotion', @obj.CleanUp );
      % Testing only:
      evalin ( 'base', 'print ( gcf, ''-dmeta'' )' );  % simulate user action in command-line
      print(hFig,'-dmeta');    % simulate programmatic printout
    end
    function Prep(obj, hFig, varargin)
      try
        hFig.ApplicationData.printPrepDone;
        return % If variable set do not run this method again
      end
      disp ( 'preparing for print.' );
      % create the date string
      str1 = sprintf ( 'Printed @ %s', datestr(now) );
      str2 = sprintf ( 'Reference: %s', obj.referenceNo );
      % create 2 UI controls to contain the information requested in the image
      hFig.ApplicationData.UIC1 = uicontrol ( 'parent',hFig, 'style','text', 'units','norm', 'string',str1, 'BackgroundColor','w', 'position',[0 0 1 0.07] );
      hFig.ApplicationData.UIC2 = uicontrol ( 'parent',hFig, 'style','text', 'units','norm', 'string',str2, 'BackgroundColor','w', 'position',[0 0.93 1 0.07] );
      % Save a temp variable to stop this function being called many times.
      hFig.ApplicationData.printPrepDone = true;
    end
    function CleanUp(obj, hFig, varargin)
      try
        if hFig.ApplicationData.printPrepDone
          % Clean up the uicontrols
          disp ( 'clean up post printing event' );
          delete ( hFig.ApplicationData.UIC1 );
          delete ( hFig.ApplicationData.UIC2 );
          % remove the temp variable, so the next print job will be captured
          hFig.ApplicationData = rmfield ( hFig.ApplicationData, 'printPrepDone' );
        end
      end
    end
  end
end
</pre>
<p>It is noted here that the datestamp and the reference number remain visible until the user interacts with the GUI but that’s a small price to pay.<br />
Any suggestions on other ways to clean up the print event afterwards? If so, please post a comment below. Alternatively if you have used events and listeners in an unusual way please share this as well.</p>
<h3 id="Conclusions">Conclusions</h3>
<ol>
<li>It is possible to capture printout events in your code even when the <i><b>print</b></i> command is invoked programmatically, without a direct reference to your code</li>
<li>We can use events for things that we might never have initially considered</li>
</ol>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/capturing-print-events">Capturing print 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/customizing-print-setup" rel="bookmark" title="Customizing print setup">Customizing print setup </a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/detecting-window-focus-events" rel="bookmark" title="Detecting window focus events">Detecting window focus events </a> <small>Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....</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>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events" rel="bookmark" title="Matlab callbacks for uifigure JavaScript events">Matlab callbacks for uifigure JavaScript events </a> <small>Matlab callback code can be attached to JavaScript events in web-based uifigures. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/capturing-print-events/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>copyobj behavior change in HG2</title>
		<link>https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=copyobj-behavior-change-in-hg2</link>
					<comments>https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 May 2015 16:00:49 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Robert Cumming]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5797</guid>

					<description><![CDATA[<p>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2">copyobj behavior change in HG2</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/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/xlsread-functionality-change-in-r2012a" rel="bookmark" title="xlsread functionality change in R2012a">xlsread functionality change in R2012a </a> <small>The functionality of the xlsread function has changed without documentation or warning in the R2012a release. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>As a followup to last-week&#8217;s post on class-object and generic data copies, I would like to welcome back guest blogger Robert Cumming, who developed a commercial <a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework">Matlab GUI framework</a>. Today, Robert will highlight a behavior change of Matlab&#8217;s <b>copyobj</b> function in HG2.</i><br />
One of the latest features that was introduced to the GUI Toolbox was the ability to <a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework/matlab-undock-uipanel">undock or copy panels</a>, that would be displayed in a standalone figure window, but remain connected to the underlying class object:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework/matlab-undock-uipanel"><img decoding="async" alt="Panel copy in the GUI framework toolbox" src="https://undocumentedmatlab.com/images/undock-02_450x412.gif" title="Panel copy in the GUI framework toolbox" width="450" height="412" /></a><figcaption class="wp-caption-text">Panel copy in the GUI framework toolbox</figcaption></figure></center><br />
These panel copies had to remain fully functional, including all children and callbacks, and they needed to retain all connections back to the source data. In the example above I have altered the plot to show that it&#8217;s an actual copy of the data, but has separate behavior from the original panel.<br />
To simply undock a uipanel to a new figure, we can simply re parent it by updating its <b>Parent</b> property to the new figure handle. To make a copy we need to utilize the <i><b>copyobj</b></i> function, rather than re-parenting. <i><b>copyobj</b></i> can be used to make a copy of all graphic objects that are &#8220;grouped&#8221; under a common parent, placing their copy in a new parent. In HG2 (R2014b onwards) the default operation of <i><b>copyobj</b></i> has changed.<br />
<span id="more-5797"></span><br />
When I started developing this feature everything looked okay and all the objects appeared copied. However, none of the callbacks were functional and all the information stored in the object&#8217;s <b>ApplicationData</b> was missing.<br />
I had used <i><b>copyobj</b></i> in the past, so I knew that it originally worked ok, so I investigated what was happening. <a target="_blank" rel="nofollow" href="http://mathworks.com/help/matlab/graphics_transition/why-are-callbacks-not-copied.html">Matlab&#8217;s documentation for HG2 code transition</a> suggests re-running the original code to create the second object to populate the callbacks. Unfortunately, this may not be suitable in all cases. Certainly in this case it would be much harder to do, than if the original callbacks had been copied directly. Another suggestion is to use the new &#8216;lagacy&#8217; option&#8217;:</p>
<blockquote><p>copyobj(___,&#8217;legacy&#8217;) copies object callback properties and object application data. This behavior is consistent with versions of copyobj before MATLAB&reg; release R2014b.</p></blockquote>
<p>So, instead of re-running the original code to create the second object to populate the callbacks, we can simply use the new &#8216;legacy&#8217; option to copy all the callbacks and <b>ApplicationData</b>:</p>
<pre lang='matlab'>copyobj(hPanel, hNewParent, 'legacy')</pre>
<p>Note: for some reason, this new &#8216;legacy&#8217; option is mentioned in both the doc page and the above-mentioned HG2 code-transition page, but not in the often used help section (<i><b>help copyobj</b></i>). There is also no link to the relevant HG2 code-transition page in either the help section or the doc page. I find it unfortunate that for such a backward-incompatible behavior change, MathWorks has not seen fit to document the information more prominently.<br />
Other things to note (this is probably not an exhaustive list…) when you are using <i><b>copyobj</b></i>:</p>
<ul>
<li>Any event listeners won&#8217;t be copied</li>
<li>Any uicontextmenus will not be copied – it will in fact behave strangely due to the fact that it will have the uicontextmenu – but the parent is the original figure – and when you right-click on the object it will change the figure focus. For example:
<pre lang='matlab'>
hFig= figure;
ax = axes;
uic = uicontextmenu ('parent', hFig);
uim = uimenu('label','My Label', 'parent',uic);
ax.UIContextMenu = uic;
copyChildren = copyobj (ax, hFig, 'legacy');
hFig2 = figure;
copyChildren.Parent = hFig2;
</pre>
</li>
</ul>
<p>Another note on undocked copies &#8211; you will need to manage your callbacks appropriately so that the callbacks manage whether they are being run by the original figure or in a new undocked figure.</p>
<h3 id="Conclusions">Conclusions</h3>
<ol>
<li><i><b>copyobj</b></i> has changed in HG2 – but the &#8220;legacy&#8221; switch allows you to use it as before.</li>
<li>It is unfortunate that backward compatibility was not fully preserved (nor documented enough) in HG2, but at least we have an escape hatch in this case.</li>
<li>Take care with the legacy option as you may need to alter uicontextmenus and re-attach listeners as required.</li>
</ol>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2">copyobj behavior change in HG2</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/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/xlsread-functionality-change-in-r2012a" rel="bookmark" title="xlsread functionality change in R2012a">xlsread functionality change in R2012a </a> <small>The functionality of the xlsread function has changed without documentation or warning in the R2012a release. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Transparency in uicontrols</title>
		<link>https://undocumentedmatlab.com/articles/transparency-in-uicontrols?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=transparency-in-uicontrols</link>
					<comments>https://undocumentedmatlab.com/articles/transparency-in-uicontrols#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Dec 2014 18:00:34 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Robert Cumming]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5302</guid>

					<description><![CDATA[<p>Matlab uicontrols' CData property can be customized to provide background transparency.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparency-in-uicontrols">Transparency in uicontrols</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/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/panel-level-uicontrols" rel="bookmark" title="Panel-level uicontrols">Panel-level uicontrols </a> <small>Matlab's uipanel contains a hidden handle to the title label, which can be modified into a checkbox or radio-button control...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/icon-images-in-matlab-uicontrols" rel="bookmark" title="Icon images &amp; text in Matlab uicontrols">Icon images &amp; text in Matlab uicontrols </a> <small>HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to welcome back guest blogger Robert Cumming, an independent UK contractor who developed a commercial class-based <a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework">Matlab GUI framework</a>. Today, Robert will highlight how he customized the use of uicontrol <b>CData</b> property.</i><br />
Before detailing how I used this feature I will start with a basic example.  A number of times (see <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/7928-matlab-gui-set-transparent-background-color-for-components">example1</a>, <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/169067">example2</a>), users have asked is it possible to set the background of uicontrols to be transparent?<br />
There are a number of reasons why we might want to do this. For example, we might wish to display a clickable image, and don&#8217;t want its background (which is typically white) to be displayed. To place on image on a uicontrol we use its <b>CData</b> property, which according to the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/uicontrol-properties.html">official Matlab documentation</a> must be a 3-D array of truecolor RGB values.<br />
Let&#8217;s start with a simple example:<br />
<figure style="width: 260px" class="wp-caption alignright"><img decoding="async" alt="uicontrol with white bgcolor" src="https://undocumentedmatlab.com/images/CData1.jpg" title="uicontrol with white bgcolor" width="260" height="225" /><figcaption class="wp-caption-text">uicontrol with white bgcolor</figcaption></figure></p>
<pre lang='matlab'>
f = figure;
img = imread('Matlab_Logo.png');
s = size(img);
pb = uicontrol('Style','pushbutton', 'Position',[10 10 s(2) s(1)], 'CData',img, ...
               'Callback',@(a,b)disp('push button'), 'BackgroundColor','green');
</pre>
<p>The code above produces the figure on the right; when we click on the image, the pushbutton callback is executed.<br />
However the background of the button is white. This is because the image is MxNx3 rectangle the size of the button.<br />
We can set the white portion of the image to be transparent so that it will show the background color of the pushbutton (in our example, &#8216;green&#8217;).<br />
First, we read the image and convert it to a 2D <i><b>double</b></i> array that ranges from 0 to 1 (the original image was RGB <i><b>uint8</b></i>, 0 to 255).  Then find the index for each RGB where the value is 1 (white):<br />
<span id="more-5302"></span></p>
<pre lang='matlab'>
img = imread('Matlab_Logo.png');
img = double(img)/255;
index1 = img(:,:,1) == 1;
index2 = img(:,:,2) == 1;
index3 = img(:,:,3) == 1;
</pre>
<p><figure style="width: 260px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uicontrol with transparent bgcolor" src="https://undocumentedmatlab.com/images/CData2.jpg" title="uicontrol with transparent bgcolor" width="260" height="225" /><figcaption class="wp-caption-text">uicontrol with transparent bgcolor</figcaption></figure><br />
The color (in this example) that we want to make transparent is where all RGB is 1, so calculate a logical index where this is true and update the <code>img</code> variable:</p>
<pre lang='matlab'>
indexWhite = index1+index2+index3==3;
for idx = 1 : 3
   rgb = img(:,:,idx);     % extract part of the image
   rgb(indexWhite) = NaN;  % set the white portion of the image to NaN
   img(:,:,idx) = rgb;     % substitute the update values
end
set(pb, 'CData', img)     % Update the CData variable
</pre>
<p>Updating the <b>CData</b> we get the image with the green background. We could set the Color of the figure to be green, to match the uicontrol&#8217;s background color:</p>
<pre lang='matlab'>set(f, 'Color', get(pb,'BackgroundColor'))</pre>
<h3 id="transparent">Transparent background</h3>
<p>As mentioned <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/7928-matlab-gui-set-transparent-background-color-for-components">here</a>, we can link the <b>CData</b> to a screenshot image of the parent figure.<br />
When we combine the two methods above, we get the effect of the uicontrol background being transparent (the smaller logo is a button that can be clicked):<br />
<figure style="width: 408px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uicontrol with transparent background (optical illusion)" src="https://undocumentedmatlab.com/images/CData3.jpg" title="uicontrol with transparent background (optical illusion)" width="408" height="380" /><figcaption class="wp-caption-text">uicontrol with transparent background (optical illusion)</figcaption></figure></p>
<pre lang='matlab'>
f = figure(); % create a figure with an axes on it
ax = axes('Units','pixels', 'Position',[0 0 560 420], 'XTick',[], 'YTick',[], ...
          'Nextplot','add', 'YDir','reverse');
% read the big logo image - background of the figure
bigImage = imread('Matlab_LogoBig.png');
image(bigImage, 'parent', ax);  % Display the image in the axes
% read a smaller image - background of button
img = imread('Matlab_Logo.png');
s = size(img);
pos = [10 10 s(2) s(1)];  %Position of the button
% Extract the portion of the image where the button will be.
F = getframe(ax,pos);  % take a screenshot of the parent figure
pb = uicontrol('Style','pushbutton', 'Units','pixels', 'Position',pos, ...
               'Callback',@(a,b)disp('push button'));
% as before - calculate where the button image is white.
img = double(img)/255;
index1 = img(:,:,1) == 1;
index2 = img(:,:,2) == 1;
index3 = img(:,:,3) == 1;
indexWhite = index1+index2+index3==3;
% for each pixel, replace the white portion with the parent image data
for idx = 1 : 3
   rgb = 1-img(:,:,idx);                   % To make the picture quirky change the RGB
   pImage = double(F.cdata(:,:,idx))/255;  % extract part of the image
   rgb(indexWhite) = pImage(indexWhite);   % set the white portion of the image to the parent
   img(:,:,idx) = rgb;                     % substitute the update values
end
% Update the push button image
set(pb, 'CData', img)
</pre>
<h3 id="checkboxes">Customizing checkboxes</h3>
<p>I have shown how to manipulate the <b>CData</b> of a button. Unfortunately, not all uicontrols have a <b>CData</b> property &#8212; the documentation states that pushbuttons and toggle buttons are the only uicontrols that are fully supported. It also mentions that you can use it in radiobuttons and checkboxes, which brings me to how I used it in my application: I use this feature on a checkbox &#8211; to use it properly we need to ensure that the size of the image we put in <b>CData</b> is 16x16x3.  In this case we set a transparent color by setting pixel RGB values to NaN:<br />
<figure style="width: 347px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uicontrol with transparent bgcolor" src="https://undocumentedmatlab.com/images/CData4.jpg" title="uicontrol with transparent bgcolor" width="347" height="172" /><figcaption class="wp-caption-text">uicontrol with transparent bgcolor</figcaption></figure></p>
<pre lang='matlab'>
f = figure('Color','red');
smiley = imread('smiley.png');
smiley = double(smiley)/255;
index1 = smiley(:,:,1) == 1;
index2 = smiley(:,:,2) == 1;
index3 = smiley(:,:,3) == 1;
indexWhite = index1+index2+index3==3;
% Create a first smiley which has the white background.
uicontrol('Style','checkbox', 'Position',[25 50 16, 16], 'CData',smiley, ...
          'Callback',@(a,b)disp('-1 smiley'));
% For each pixel, replace the white portion with the parent image data
for idx = 1 : 3
   rgb = smiley(:,:,idx);  % To make the picture quirky change the RGB
   rgb(indexWhite) = NaN;
   smiley(:,:,idx) = rgb;  % substitute the update values.
end
% Create a second smiley which has the transparent background.
uicontrol('Style','checkbox', 'Position',[25 25 16, 16], 'CData',smiley, ...
          'Callback',@(a,b)disp('+1 smiley'), 'BackgroundColor','red');
</pre>
<p>The upper smiley is the original image; the lower smiley has its white pixels set to NaN, and the background colors of the control and the figure set to equal. The checkbox has no text is displayed, the user just clicks on the smiley to invoke the callback.<br />
Note: This trick works in R2014b but I have deliberately used old style <i><b>set</b></i> and <i><b>get</b></i> commands for compatibility with older versions of Matlab. I have used this in all versions from R2008a onwards, and I suspect it probably works in older versions as well.<br />
I used this feature several times in my Matlab GUI Toolbox. One of the uses was to create a pin for locking a dynamic panel in position: The panel is by default hidden; when the user hovers the mouse near the edge, the dynamic panel appears after some predefined time (2 seconds). A checkbox with a manipulated <b>CData</b> masquerades as a pin for locking the panel in position. When the panel is pinned, the <b>CData</b> changes accordingly:<br />
<center><img decoding="async" alt="transparent uicontrol usage example" src="https://undocumentedmatlab.com/images/panel_pin.png" title="transparent uicontrol usage example" width="90%" style="max-width:889px;" /><br />
transparent uicontrol usage example</center></p>
<h3 id="Conclusions">Conclusions</h3>
<p>1. The <b>CData</b> property of a uicontrol can be set to NaN to imitate transparent behavior.<br />
2. By linking this with the parent <b>CData</b> we can super-impose an image on top of  another image.<br />
3. We can customize other uicontrols using the method to turn checkboxes (for example) into clickable images.<br />
Have you used this feature?  If so please share in a comment below.<br />
<i><u>Editor&#8217;s note</u>: I have shown another alternative for displaying clickable transparent images in my article on <a target="_blank" href="/articles/displaying-animated-gifs">displaying animated/transparent GIFs</a>. Readers might also find interest in the related article on <a target="_blank" href="/articles/transparent-uipanels">transparent uipanels</a>. Next week I plan to show how MathWorkers Ben Tordoff and David Sampson coerced a simple checkbox uicontrol to have a radically different appearance, as flex-panel dividers in their GUI Layout Toolbox, similarly to what Robert explained today. Stay tuned! &nbsp;&#8211; Yair</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparency-in-uicontrols">Transparency in uicontrols</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/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/panel-level-uicontrols" rel="bookmark" title="Panel-level uicontrols">Panel-level uicontrols </a> <small>Matlab's uipanel contains a hidden handle to the title label, which can be modified into a checkbox or radio-button control...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/icon-images-in-matlab-uicontrols" rel="bookmark" title="Icon images &amp; text in Matlab uicontrols">Icon images &amp; text in Matlab uicontrols </a> <small>HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/transparency-in-uicontrols/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>uicontextmenu performance</title>
		<link>https://undocumentedmatlab.com/articles/uicontextmenu-performance?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=uicontextmenu-performance</link>
					<comments>https://undocumentedmatlab.com/articles/uicontextmenu-performance#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Apr 2014 18:00:29 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Robert Cumming]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4751</guid>

					<description><![CDATA[<p>Matlab uicontextmenus are not automatically deleted with their associated objects, leading to leaks and slow-downs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uicontextmenu-performance">uicontextmenu performance</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/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/zero-testing-performance" rel="bookmark" title="Zero-testing performance">Zero-testing performance </a> <small>Subtle changes in the way that we test for zero/non-zero entries in Matlab can have a significant performance impact. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to introduce guest blogger Robert Cumming, an <a target="_blank" rel="nofollow" href="http://www.matpi.com">independent contractor</a> based in the UK who has recently worked on certification of the newest advanced civil aircraft. Today Robert will discuss the performance of <b>uicontextmenu</b>s in interactive GUIs, which were used extensively in flight test analysis.</i><br />
Have you ever noticed that a GUI slows down over time?  I was responsible for designing a highly complex interactive GUI, which plotted flight test data for engineers and designers to analyze data for comparison with pre-flight predictions. This involved extensive plotting of data (pressure, forces/moments, anemometry, actuator settings etc&#8230;.), where individual data points were required to have specific/customizable uicontextmenus.<br />
Matlab&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/uicontextmenu.html">documentation on uicontextmenus</a> discusses adding them to plots, but makes no mention of the cleaning up afterwards.<br />
Let&#8217;s start with some GUI basics. First we create a figure with a simple axes and a line:</p>
<pre lang='matlab'>
x = [-10:0.2:10];
y = x.^2;
h = figure;
ax = axes ( 'parent',h );
hplot = plot ( ax, x, y );
</pre>
<p>Adding a uicontextmenu to the plot creates extra objects:</p>
<pre lang='matlab'>
uic = uicontextmenu;
uimenu ( uic, 'Label','Menu A.1' );
set ( hplot, 'uicontextmenu',uic );
fprintf ( 'Figure (h) has %i objects\n', length ( findobj ( h ) ) );
</pre>
<p>In this instance there are 5 objects, the individual menu and uicontextmenu have created an additional 2 objects.  All of this is quite basic as you would expect.<br />
<center><figure style="width: 250px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Basic plot with a custom context menu" src="https://undocumentedmatlab.com/images/uicontextmenu1.png" title="Basic plot with a custom context menu" width="250" height="170" /><figcaption class="wp-caption-text">Basic plot with a custom context menu</figcaption></figure></center><br />
<span id="more-4751"></span><br />
We now clear the plot using <i><b>cla</b></i> and draw a new line with its own new uicontextmenu. Note that we don&#8217;t save the plot handle this time:</p>
<pre lang='matlab'>
cla ( ax );
uic = uicontextmenu;
uimenu ( uic, 'Label','Menu B.1' );
plot ( ax, x, -y , 'uicontextmenu',uic );
fprintf ( 'Figure (h) has %i objects\n', length ( findobj ( h ) ) );
</pre>
<p><center><figure style="width: 250px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Another basic plot with a new context menu" src="https://undocumentedmatlab.com/images/uicontextmenu2.png" title="Another basic plot with a new context menu" width="250" height="170" /><figcaption class="wp-caption-text">Another basic plot with a new context menu</figcaption></figure></center><br />
This time the <i><b>fprintf</b></i> line tells us that the figure has 7 objects. This may not have been expected, as the first plot was cleared and the original context menu is no longer accessible (<i><b>cla</b></i> removed the plot and the line object hplot).<br />
Let&#8217;s check these object handles:</p>
<pre lang='matlab'>
>> ishandle ( findobj( h ) )'
ans =
     1     1     1     1     1     1     1     1     1     1     1     1     1
</pre>
<p>We see that all the objects are valid handles. At first this may perhaps appear confusing: after all, the plot with &#8220;Menu A.1&#8221; was deleted. Let&#8217;s check this:</p>
<pre lang='matlab'>
>> ishandle ( hplot )
ans =
     0
>> get(hplot)
Error using handle.handle/get
Invalid or deleted object.
</pre>
<p>So it appears that although the plot line was indeed deleted, its associated context menu was not. The reason for this is that the context menu is created as a child of the figure window, not the plot. We are simply using the plot line&#8217;s <b>UIContextMenu</b> property to allow the user to obtain access to it and its associated menus.<br />
Once we understand this we can do two things:</p>
<ol>
<li>Use the same uicontextmenu for each plot</li>
<li>Built individual uicontextmenus for each plot, but remember to clean up afterwards</li>
</ol>
<h3 id="importance">Is this really such a big issue?</h3>
<p>You may be wondering how big a problem is this creation of extra objects. The answer is that for simple cases like this it is really not a big issue. But let&#8217;s consider a more realistic case where we also <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/creating_guis/writing-code-for-callbacks.html">assign callbacks</a> to the menus. First we will create a figure with an axes, for plotting on and a uicontrol edit for displaying a message:</p>
<pre lang='matlab'>
function uicontextExample
   h.main = figure;
   h.ax = axes ( 'parent',h.main, 'NextPlot','add', 'position',[0.1 0.2 0.8 0.7] );
   h.msg = uicontrol ( 'style','edit', 'units','normalized', 'position',[0.08 0.01 0.65 0.1], 'backgroundcolor','white' );
   uicontrol ( 'style','pushbutton', 'units','normalized', 'position',[0.75 0.01 0.2 0.1], 'Callback',{@RedrawX20 h}, 'string','re-draw x20' );
   redraw ( [], [], h )  % see below
end
</pre>
<p>The callback <code>redraw</code> (shown below) draws a simple curve and assigns individual uicontextmenus to each individual item in the plot. Each uicontextmenu has 12 menu items:</p>
<pre lang='matlab'>
function redraw ( obj, event, h, varargin )
   cla(h.ax);
   start = tic;
   x = -50:50;
   y = x.^2;
   for ii = 1 : length(x)
      uim = uicontextmenu ( 'parent',h.main );
      for jj = 1 : 10
         menuLabel = sprintf ( 'Menu %i.%i', ii, jj );
         uimenu ( 'parent',uim, 'Label',menuLabel, 'Callback',{@redraw h} )
      end
      xStr = sprintf ( 'X = %f', x(ii) );
      yStr = sprintf ( 'Y = %f', y(ii) );
      uimenu ( 'parent',uim, 'Label',xStr, 'Callback',{@redraw h} )
      uimenu ( 'parent',uim, 'Label',yStr, 'Callback',{@redraw h} )
      plot ( h.ax, x(ii), y(ii), 'rs', 'uicontextmenu',uim );
   end
   objs = findobj ( h.main );
   s = sprintf ( 'figure contains %i objects - drawn in %3.2f seconds', length(objs), toc(start) );
   set ( h.msg, 'string',s );
   fprintf('%s\n',s)
end
</pre>
<p>To help demonstrate the slow-down in speed, the pushbutton uicontrol will redraw the plot 20 times, and show the results from the profiler:</p>
<pre lang='matlab'>
function RedrawX20 ( obj, event, h )
   profile on
   set ( obj, 'enable','off' )
   for ii = 1 : 20
      redraw ( [], [], h );
      drawnow();
   end
   set ( obj, 'enable','on' )
   profile viewer
end
</pre>
<p>The first time we run this, on a reasonable laptop it takes 0.24 seconds to draw the figure with all the menus:<br />
<center><figure style="width: 380px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Multiple context menus assigned to individual data points" src="https://undocumentedmatlab.com/images/uicontextmenu3.png" title="Multiple context menus assigned to individual data points" width="380" height="190" /><figcaption class="wp-caption-text">Multiple context menus assigned to individual data points</figcaption></figure></center><br />
When we press the &lt;re-draw x20&gt; button we get:</p>
<pre lang='matlab'>
figure contains 2731 objects - drawn in 0.28 seconds
figure contains 4044 objects - drawn in 0.28 seconds
figure contains 5357 objects - drawn in 0.28 seconds
figure contains 6670 objects - drawn in 0.30 seconds
figure contains 7983 objects - drawn in 0.32 seconds
figure contains 9296 objects - drawn in 0.30 seconds
figure contains 10609 objects - drawn in 0.31 seconds
figure contains 11922 objects - drawn in 0.30 seconds
figure contains 13235 objects - drawn in 0.32 seconds
figure contains 14548 objects - drawn in 0.30 seconds
figure contains 15861 objects - drawn in 0.31 seconds
figure contains 17174 objects - drawn in 0.31 seconds
figure contains 18487 objects - drawn in 0.32 seconds
figure contains 19800 objects - drawn in 0.33 seconds
figure contains 21113 objects - drawn in 0.32 seconds
figure contains 22426 objects - drawn in 0.33 seconds
figure contains 23739 objects - drawn in 0.35 seconds
figure contains 25052 objects - drawn in 0.34 seconds
figure contains 26365 objects - drawn in 0.35 seconds
figure contains 27678 objects - drawn in 0.35 seconds
</pre>
<p>The run time shows significant degradation, and we have many left-over objects. The profiler output confirms where the time is being spent:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Profiling results - context menu creation is an evident hotspot" src="https://undocumentedmatlab.com/images/uicontextmenu4.png" title="Profiling results - context menu creation is an evident hotspot" width="450" height="285" /><figcaption class="wp-caption-text">Profiling results - context menu creation is an evident hotspot</figcaption></figure></center><br />
As expected the menus creation takes most of the time. Note that the timing that you will get on your own computer for this example may vary and the slowdown may be less noticeable.<br />
Let&#8217;s extend the example to include extra input arguments in the callback  (in this example they are not used &#8211; but in the industrial example extra input arguments are very possible, and were required by the customer):</p>
<pre lang='matlab'>
for ii=1:length(x)
   uim = uicontextmenu ( 'parent',h.main );
   for jj = 1 : 10
      menuLabel = sprintf ( 'Menu %i.%i', ii, jj );
      uimenu ( 'parent',uim, 'Label',menuLabel, 'Callback',{@redraw h 1 0 1} )
   end
   xStr = sprintf ( 'X = %f', x(ii) );
   yStr = sprintf ( 'Y = %f', y(ii) );
   uimenu ( 'parent',uim, 'Label',xStr, 'Callback',{@redraw h 1 0 1} )
   uimenu ( 'parent',uim, 'Label',yStr, 'Callback',{@redraw h 1 0 1} )
   plot ( h.ax, x(ii), y(ii), 'rs', 'uicontextmenu',uim );
end
</pre>
<p>Re-running the code and pressing &lt;re-draw x20&gt; we get:</p>
<pre lang='matlab'>
figure contains 1418 objects - drawn in 0.29 seconds
figure contains 2731 objects - drawn in 0.37 seconds
figure contains 4044 objects - drawn in 0.48 seconds
figure contains 5357 objects - drawn in 0.65 seconds
...
figure contains 23739 objects - drawn in 4.99 seconds
figure contains 25052 objects - drawn in 5.34 seconds
figure contains 26365 objects - drawn in 5.88 seconds
figure contains 27678 objects - drawn in 6.22 seconds
</pre>
<p>Note that the 6.22 seconds is just the time that it took the last individual redraw, not the total time to draw 20 times (which was just over a minute). The profiler is again used to confirm that the vast majority of the time (57 seconds) was spent in the <i><b>uimenu</b></i> calls, mostly on line #23. In comparison, all other lines together took just 4 seconds to run.<br />
The simple act of adding extra inputs to the callback has completely transformed the speed of our code.<br />
How real is this example?<br />
In code written for a customer, the context menu had a variety of sub menus (dependent on the parameter being plotted &#8211; from 5 to ~20), and they each had multiple parameters passed into the callbacks. Over a relatively short period of time the user would cycle through a lot of data and the number of uicontextmenus being created was surprisingly large. For example, users would easily look at 100 individual sensors recorded at 10Hz for 2 minutes (100*10*60*2). If all sensors and points are plotted individually that would be 120,000 uicontextmenus!</p>
<h3 id="solution">So how do we resolve this?</h3>
<p>The problem is addressed by simply deleting the context menu handles once they are no longer needed. This can be done by adding a <i><b>delete</b></i> command after <i><b>cla</b></i> at the top of the <code>redraw</code> function, in order to remove the redundant uicontextmenus:</p>
<pre lang='matlab' highlight='3'>
function redraw ( obj, event, h, varargin )
   cla(h.ax);
   delete ( findobj ( h.main, 'type','uicontextmenu' ) )
   set ( h.msg, 'string','redrawing' );
   start = tic;
   ...
</pre>
<p>If we now click &lt;redraw x20&gt; we see that the number of objects and the time to create them remain its essentially the same as the first call: 1418 objects and 0.28 seconds:</p>
<pre lang='matlab'>
figure contains 1418 objects - drawn in 0.28 seconds
figure contains 1418 objects - drawn in 0.30 seconds
figure contains 1418 objects - drawn in 0.33 seconds
figure contains 1418 objects - drawn in 0.29 seconds
figure contains 1418 objects - drawn in 0.29 seconds
...
</pre>
<p>Advanced users could use <a target="_blank" href="/articles/udd-events-and-listeners/">handle listeners</a> to attached a callback such that when a plot element is deleted, so too are its associated context menus.</p>
<h3 id="conclusions">Conclusions</h3>
<p>Things to consider with uicontextmenus:</p>
<ol>
<li>Always delete uicontextmenus that you have finished with.</li>
<li>If you have multiple uicontextmenus  you will want to only delete the ones associated with the axes being cleared &#8211; otherwise you will delete more than you want to.</li>
<li>Try to reduce the number of input arguments to your callbacks, group into a structure or cell array.</li>
<li>Re-use uicontextmenus where possible.</li>
</ol>
<p>Have you had similar experiences?  Or other issues where GUI slow down over time? If so, please leave a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uicontextmenu-performance">uicontextmenu performance</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/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/zero-testing-performance" rel="bookmark" title="Zero-testing performance">Zero-testing performance </a> <small>Subtle changes in the way that we test for zero/non-zero entries in Matlab can have a significant performance impact. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/uicontextmenu-performance/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
