<?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>Handle graphics &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/category/handle-graphics/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Thu, 07 Nov 2019 13:43:36 +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>Improving graphics interactivity</title>
		<link>https://undocumentedmatlab.com/articles/improving-graphics-interactivity?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=improving-graphics-interactivity</link>
					<comments>https://undocumentedmatlab.com/articles/improving-graphics-interactivity#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 21 Apr 2019 21:03:10 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Toolbar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8723</guid>

					<description><![CDATA[<p>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity">Improving graphics interactivity</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</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/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab release R2018b added the concept of <a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" target="_blank">axes-specific toolbars</a> and default <a href="https://www.mathworks.com/help/matlab/creating_plots/control-axes-interactions.html" rel="nofollow" target="_blank">axes mouse interactivity</a>. <span class="alignright"><img decoding="async" src="https://undocumentedmatlab.com/images/speedometer4d_200x200.gif" alt="Accelerating MATLAB Performance" title="Accelerating MATLAB Performance" width="200" height="200" /></span> Plain 2D plot axes have the following default interactions enabled by default: <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.paninteraction.html" rel="nofollow" target="_blank">PanInteraction</a>, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.zoominteraction.html" rel="nofollow" target="_blank">ZoomInteraction</a>, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.datatipinteraction.html" rel="nofollow" target="_blank">DataTipInteraction</a> and <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.rulerpaninteraction.html" rel="nofollow" target="_blank">RulerPanInteraction</a>.</p>
<p>Unfortunately, I find that while the default interactions set is much more useful than the non-interactive default axes behavior in R2018a and earlier, it could still be improved in two important ways:</p>
<ol>
<li><b>Performance</b> &#8211; Matlab&#8217;s builtin Interaction objects are very inefficient. In cases of multiple overlapping axes (which is very common in multi-tab GUIs or cases of various types of axes), instead of processing events for just the top visible axes, they process all the enabled interactions for *all* axes (including non-visible ones!). This is particularly problematic with the default DataTipInteraction &#8211; it includes a <code>Linger</code> object whose apparent purpose is to detect when the mouse lingers for enough time on top of a chart object, and displays a data-tip in such cases. Its internal code is both inefficient and processed multiple times (for each of the axes), as can be seen via a profiling session.</li>
<li><b>Usability</b> &#8211; In my experience, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.regionzoominteraction.html" rel="nofollow" target="_blank">RegionZoomInteraction</a> (which enables defining a region zoom-box via click-&#038;-drag) is usually much more useful than PanInteraction for most plot types. ZoomInteraction, which is enabled by default only enables zooming-in and -out using the mouse-wheel, which is much less useful and more cumbersome to use than RegionZoomInteraction. The panning functionality can still be accessed interactively with the mouse by dragging the X and Y rulers (ticks) to each side.</li>
</ol>
<p>For these reasons, I typically use the following function whenever I create new axes, to replace the default sluggish DataTipInteraction and PanInteraction with RegionZoomInteraction:<br />
<span id="more-10306"></span></p>
<pre lang="matlab">
function axDefaultCreateFcn(hAxes, ~)
    try
        hAxes.Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
        hAxes.Toolbar = [];
    catch
        % ignore - old Matlab release
    end
end
</pre>
<p>The purpose of these two axes property changes shall become apparent below.<br />
This function can either be called directly (<code>axDefaultCreateFcn(hAxes</code>), or as part of the containing figure&#8217;s creation script to ensure than any axes created in this figure has this fix applied:</p>
<pre lang="matlab">
set(hFig,'defaultAxesCreateFcn',@axDefaultCreateFcn);
</pre>
<h3 id="testing">Test setup</h3>
<p><figure style="width: 268px" class="wp-caption alignright"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/Axes_Interactivity.png" alt="Figure with default axes toolbar and interactivity" title="Figure with default axes toolbar and interactivity" width="268" height="200" /><figcaption class="wp-caption-text">Figure with default axes toolbar and interactivity</figcaption></figure> To test the changes, let&#8217;s prepare a figure with 10 tabs, with 10 overlapping panels and a single axes in each tab:</p>
<pre lang="matlab">
hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel); %see MLint note below
    plot(hAxes(iTab),1:5,'-ob');
end
drawnow
</pre>
<p style="padding-left: 20px; margin-top: -15px;"><i><font size=-1>p.s. &#8211; there&#8217;s a incorrect MLint (Code Analyzer) warning in line 9 about the call to axes(hPanel) being inefficient in a loop. Apparently, MLint incorrectly parses this function call as a request to make the axes in-focus, rather than as a request to create the axes in the specified hPanel parent container. We can safely ignore this warning.</font></i></p>
<p>Now let&#8217;s create a run-time test script that simulates 2000 mouse movements using <a href="https://undocumentedmatlab.com/articles/gui-automation-robot" target="_blank">java.awt.Robot</a>:</p>
<pre lang="matlab">
tic
monitorPos = get(0,'MonitorPositions');
y0 = monitorPos(1,4) - 200;
robot = java.awt.Robot;
for iEvent = 1 : 2000
    robot.mouseMove(150, y0+mod(iEvent,100));
    drawnow
end
toc
</pre>
<p>This takes ~45 seconds to run on my laptop: ~23ms per mouse movement on average, with noticeable &#8220;linger&#8221; when the mouse pointer is near the plotted data line. Note that this figure is extremely simplistic &#8211; In a real-life program, the mouse events processing lag the mouse movements, making the GUI far more sluggish than the same GUI on R2018a or earlier. In fact, in one of my more complex GUIs, the entire GUI and Matlab itself came to a standstill that required killing the Matlab process, just by moving the mouse for several seconds.</p>
<p>Notice that at any time, only a single axes is actually visible in our test setup. The other 9 axes are not visible although their <b>Visible</b> property is <code>'on'</code>. Despite this, when the mouse moves within the figure, these other axes unnecessarily process the mouse events.</p>
<h3 id="interactions">Changing the default interactions</h3>
<p>Let&#8217;s modify the axes creation script as I mentioned above, by changing the default interactions (note the highlighted code addition):</p>
<pre lang="matlab" highlight="11">
hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel);
    plot(hAxes(iTab),1:5,'-ob');
    hAxes(iTab).Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
end
drawnow
</pre>
<p>The test script now takes only 12 seconds to run &#8211; 4x faster than the default and yet IMHO with better interactivity (using RegionZoomInteraction).</p>
<h3 id="Toolbar">Effects of the axes toolbar</h3>
<p>The axes-specific toolbar, another innovation of R2018b, does not just have interactivity aspects, which are by themselves <a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" target="_blank">much-contested</a>. A much less discussed aspect of the axes toolbar is that it degrades the overall performance of axes. The reason is that the axes toolbar&#8217;s transparency, visibility, background color and contents continuously update whenever the mouse moves within the axes area.</p>
<p>Since we have set up the default interactivity to a more-usable set above, and since we can replace the axes toolbar with figure-level toolbar controls, we can simply delete the axes-level toolbars for even more-improved performance:</p>
<pre lang="matlab" highlight="12">
hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel);
    plot(hAxes(iTab),1:5,'-ob');
    hAxes(iTab).Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
    hAxes(iTab).Toolbar = [];
end
drawnow
</pre>
<p>This brings the test script&#8217;s run-time down to 6 seconds &#8211; <b>7x faster than the default run-time</b>. At ~3ms per mouse event, the GUI is now as performant and snippy as in R2018a, even with the new interactive mouse actions of R2018b active.</p>
<h3 id="Conclusions">Conclusions</h3>
<p>MathWorks definitely did not intend for this slow-down aspect, but it is an unfortunate by-product of the choice to auto-enable DataTipInteraction and of its sub-optimal implementation. Perhaps this side-effect was never noticed by MathWorks because the testing scripts probably had only a few axes in a very simple figure &#8211; in such a case the performance lags are very small and might have slipped under the radar. But I assume that many real-life complex GUIs will display significant lags in R2018b and newer Matlab releases, compared to R2018a and earlier releases. I assume that such users will be surprised/dismayed to discover that in R2018b their GUI not only interacts differently but also runs slower, although the program code has not changed.</p>
<p>One of the common claims that I often hear against using undocumented Matlab features is that the program might break in some future Matlab release that would not support some of these features. But users certainly do not expect that their programs might break in new Matlab releases when they only use documented features, as in this case. IMHO, this case (and others over the years) demonstrates that using undocumented features is usually not much riskier than using the standard documented features with regards to future compatibility, making the risk/reward ratio more favorable. In fact, of the ~400 posts that I have published in the past decade (this blog is already 10 years old, time flies&#8230;), very few tips no longer work in the latest Matlab release. When such forward compatibility issues do arise, whether with fully-documented or undocumented features, we can often find workarounds as I have shown above.</p>
<p>If your Matlab program could use a performance boost, I would be happy to assist making your program faster and more responsive. Don&#8217;t hesitate to reach out to me for a consulting quote.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity">Improving graphics interactivity</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</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/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/improving-graphics-interactivity/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented plot marker types</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-plot-marker-types</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Mar 2019 11:05:14 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8539</guid>

					<description><![CDATA[<p>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</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/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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/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>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I wanted to take a break from my miniseries on the Matlab toolstrip to describe a nice little undocumented aspect of plot line markers. Plot line marker types have remained essentially unchanged in user-facing functionality for the past two+ decades, allowing the well-known marker types (.,+,o,^ etc.). Internally, lots of things changed in the graphics engine, particularly in the <a href="https://undocumentedmatlab.com/articles/hg2-update" target="_blank">transition to HG2</a> in R2014b and the <a href="https://blogs.mathworks.com/graphics/2015/11/10/memory-consumption/#comment-465" rel="nofollow" target="_blank">implementation of markers using OpenGL primitives</a>. I suspect that during the massive amount of development work that was done at that time, important functionality improvements that were implemented in the engine were forgotten and did not percolate all the way up to the user-facing functions. I highlighted a few of these in the past, for example transparency and color gradient for <a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" target="_blank">plot lines</a> and <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">markers</a>, or <a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" target="_blank">various aspects of contour plots</a>.<br />
Fortunately, Matlab usually exposes the internal objects that we can customize and which enable these extra features, in hidden properties of the top-level graphics handle. For example, the standard Matlab plot-line handle has a hidden property called <b>MarkerHandle</b> that we can access. This returns an internal object that enables <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">marker transparency and color gradients</a>. We can also use this object to set the marker style to a couple of formats that are not available in the top-level object:</p>
<pre lang="matlab">
>> x=1:10; y=10*x; hLine=plot(x,y,'o-'); box off; drawnow;
>> hLine.MarkerEdgeColor = 'r';
>> set(hLine, 'Marker')'  % top-level marker styles
ans =
  1×14 cell array
    {'+'} {'o'} {'*'} {'.'} {'x'} {'square'} {'diamond'} {'v'} {'^'} {'>'} {'<'} {'pentagram'} {'hexagram'} {'none'}
>> set(hLine.MarkerHandle, 'Style')'  % low-level marker styles
ans =
  1×16 cell array
    {'plus'} {'circle'} {'asterisk'} {'point'} {'x'} {'square'} {'diamond'} {'downtriangle'} {'triangle'} {'righttriangle'} {'lefttriangle'} {'pentagram'} {'hexagram'} {'vbar'} {'hbar'} {'none'}
</pre>
<p>We see that the top-level marker styles directly correspond to the low-level styles, except for the low-level &#8216;vbar&#8217; and &#8216;hbar&#8217; styles. Perhaps the developers forgot to add these two styles to the top-level object in the enormous upheaval of HG2. Luckily, we can set the hbar/vbar styles directly, using the line&#8217;s <b>MarkerHandle</b> property:</p>
<pre lang="matlab">
hLine.MarkerHandle.Style = 'hbar';
set(hLine.MarkerHandle, 'Style','hbar');  % alternative
</pre>
<p><center><figure style="width: 213px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/plot_hbar.png" alt="hLine.MarkerHandle.Style='hbar'" title="hLine.MarkerHandle.Style='hbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='hbar'</figcaption></figure> <figure style="width: 213px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/plot_vbar.png" alt="hLine.MarkerHandle.Style='vbar'" title="hLine.MarkerHandle.Style='vbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='vbar'</figcaption></figure></center></p>
<h3 id="USA">USA visit</h3>
<p>I will be travelling in the US in May/June 2019. Please let me know (altmany at gmail) if you would like to schedule a meeting or onsite visit for consulting/training, or perhaps just to explore the possibility of my professional assistance to your Matlab programming needs.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</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/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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/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>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Plot legend customization</title>
		<link>https://undocumentedmatlab.com/articles/plot-legend-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=plot-legend-customization</link>
					<comments>https://undocumentedmatlab.com/articles/plot-legend-customization#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 12 Jul 2018 14:11:40 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7744</guid>

					<description><![CDATA[<p>Matlab plot legends and their internal components can be customized using a variety of undocumented properties that are easily accessible. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-customization">Plot legend customization</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/plot-legend-title" rel="bookmark" title="Plot legend title">Plot legend title </a> <small>Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" rel="bookmark" title="Plot line transparency and color gradient">Plot line transparency and color gradient </a> <small>Static and interpolated (gradient) colors and transparency can be set for plot lines in HG2. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Three years ago I <a href="/articles/plot-legend-title" target="_blank">explained</a> how we can use a couple of undocumented hidden properties of the legend in order to add a legend title (the legend object had no <b>Title</b> property back then &#8211; this was only added in a later Matlab release, perhaps as a result of my post). Today I will expand on that article by explaining the plot legend&#8217;s internal graphics hierarchy, how we can access each of these components, and then how this information could be used to customize the separate legend components. Note that the discussion today is only relevant for HG2 legends (i.e. R2014b or newer).<br />
Let&#8217;s start with a simple Matlab plot with a legend:</p>
<pre lang="matlab">
hold all;
hLine1 = plot(1:5);
hLine2 = plot(2:6);
hLegend = legend([hLine1,hLine2], 'Location','SouthEast');
hLegend.Title.String = 'MyLegend';
</pre>
<p><center><figure style="width: 210px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_1.gif" alt="Standard Matlab legend" title="Standard Matlab legend" width="210" height="145" /><figcaption class="wp-caption-text">Standard Matlab legend</figcaption></figure></center> This legend is composed of the following visible internal components, which can be customized separately:<br />
<center><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></center><br />
<span id="more-7744"></span><br />
<!-- center>[caption id="" align="aligncenter" width="150" caption="Matlab legend components"]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" />[/caption]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></center --><br />
<!-- span class="alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></span --></p>
<table>
<tr>
<th align="left">Id in screenshot</th>
<th align="left">Accessed via</th>
<th align="left">Object type</th>
<th align="left">Description</th>
<th align="left">Important properties</th>
</tr>
<tr>
<td>1</td>
<td><code>hLegend.Title</code></td>
<td><code>Text</code></td>
<td>Title of the legend</td>
<td><b>Visible</b>, <b>String</b>, <b>Color</b>, <b>FontSize</b>, <b>FontWeight</b>.</td>
</tr>
<tr>
<td>2</td>
<td><code>hLegend.TitleSeparator</code></td>
<td><code>LineStrip</code></td>
<td>Separator line between title and legend entries. Only appears when title is set.</td>
<td><b>Visible</b>, <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8)</td>
</tr>
<tr>
<td>3</td>
<td><code>hLegend.BoxEdge</code></td>
<td><code>LineLoop</code></td>
<td>Box (border) line around the entire legend (including title)</td>
<td><b>Visible</b>, <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8)</td</td>
</tr>
<tr>
<td>4</td>
<td><code>hLegend.EntryContainer.NodeChildren(2)</code></td>
<td><code>LegendEntry</code></td>
<td>Entry row in the legend, corresponding to <code>hLine1</code></td>
<td><b>Icon</b>, <b>Label</b>, <b>Object</b> (line object in main axes)</td>
</tr>
<tr>
<td>5</td>
<td><code>hLegend.EntryContainer.NodeChildren(1)</code></td>
<td><code>LegendEntry</code></td>
<td>Entry row in the legend, corresponding to <code>hLine2</code></td>
<td><b>Icon</b>, <b>Label</b>, <b>Object</b> (line object in main axes)</td>
</tr>
<tr>
<td>6</td>
<td><code>hLegend.EntryContainer.NodeChildren(1).Label</code></td>
<td><code>Text</code></td>
<td>Label of legend entry</td>
<td><b>Visible</b>, <b>String</b>, <b>Color</b>, <b>FontSize</b>, <b>FontWeight</b></td>
</tr>
<tr>
<td>7</td>
<td><code>hLegend.EntryContainer.NodeChildren(1).Icon</code></td>
<td><code>LegendIcon</code></td>
<td>Icon/marker of legend entry</td>
<td><b>Visible</b>, <b>Transform.Children.Children</b> (<code>LineStrip</code> object)</td>
</tr>
</table>
<p>A pivotal object of the legend group are the <code>LegendEntry</code> items, one per legend row:</p>
<pre lang="matlab">
>> hLegendEntry = hLegend.EntryContainer.NodeChildren(1);
>> get(hLegendEntry)
              Children: [3×1 Graphics]
                 Color: [0 0 0]
                 Dirty: 0
             FontAngle: 'normal'
              FontName: 'Helvetica'
              FontSize: 8
            FontWeight: 'normal'
      HandleVisibility: 'on'
               HitTest: 'on'
                  Icon: [1×1 LegendIcon]
                 Index: 0
           Interpreter: 'tex'
                 Label: [1×1 Text]
            LayoutInfo: [1×1 matlab.graphics.illustration.legend.ItemLayoutInfo]
                Legend: [1×1 Legend]
              Listener: [1×1 event.listener]
                Object: [1×1 Line]
               Overlay: [1×1 TriangleStrip]
          OverlayAlpha: 0.65
                Parent: [1×1 Group]
           PeerVisible: 'on'
         PickableParts: 'visible'
              Selected: 'off'
    SelectionHighlight: 'on'
               Visible: 'on'
       VisibleListener: [1×1 event.proplistener]
</pre>
<p>Each <code>LegendEntry</code> contains a back-reference to the original graphics object. In my example above, <code>hLegend.EntryContainer.NodeChildren(2).Object == hLine1</code>, and <code>hLegend.EntryContainer.NodeChildren(2).Object == hLine1</code>. Note how the default legend entries order is the reverse of the order of creation of the original graphics objects. Naturally, we can modify this order by creating the legend py passing it an array of handles that is ordered differently (see the documentation of the <i><b>legend</b></i> function).<br />
To get all the original graphic objects together, in a single array, we could use one of two mechanisms (note the different order of the returned objects):</p>
<pre lang="matlab">
% Alternative #1
>> [hLegend.EntryContainer.NodeChildren.Object]'
ans =
  2×1 Line array:
  Line    (data2)
  Line    (data1)
% Alternative #2
>> hLegend.PlotChildren
ans =
  2×1 Line array:
  Line    (data1)
  Line    (data2)
</pre>
<p>For some reason, accessing the displayed graphic line in <code>LegendEntry</code>&#8216;s <b>Icon</b> is not simple. For example, the <code>LineStrip</code> object that corresponds to <code>hLine2</code> can be gotten via:</p>
<pre lang="matlab">
hLegendEntry = hLegend.EntryContainer.NodeChildren(1);
hLegendIconLine = hLegendEntry.Icon.Transform.Children.Children;  % a LineStrip object in our example
</pre>
<p>I assume that this was done to enable non-standard icons for patches and other complex objects (in which case the displayed icon would not necessarily be a <code>LineStrip</code> object). In the case of a line with markers, for example, <code>hLegendIconLine</code> would be an array of 2 objects: a <code>LineStrip</code> object and a separate <code>Marker</code> object. Still, I think that a direct reference in a <code>hLegend.EntryContainer.NodeChildren(1).Icon</code> property would have helped in 99% of all cases, so that we wouldn&#8217;t need to pass through the <code>Transform</code> object.<br />
Anyway, once we have this object reference(s), we can modify its/their properties. In the case of a <code>LineStrip</code> this includes <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8), and <b>VertexData</b> (which controls position/length):</p>
<pre lang="matlab">
>> get(hLegendIconLine(end))  % LineStrip
          AlignVertexCenters: 'on'
             AmbientStrength: 0.3
                ColorBinding: 'object'
                   ColorData: [4×1 uint8]
                   ColorType: 'truecolor'
             DiffuseStrength: 0.6
            HandleVisibility: 'on'
                     HitTest: 'off'
                       Layer: 'middle'
                     LineCap: 'none'
                    LineJoin: 'round'
                   LineStyle: 'solid'
                   LineWidth: 0.5
               NormalBinding: 'none'
                  NormalData: []
                      Parent: [1×1 Group]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: []
                     Texture: [0×0 GraphicsPlaceholder]
                  VertexData: [3×2 single]
               VertexIndices: []
                     Visible: 'on'
       WideLineRenderingHint: 'software'
</pre>
<p>and in the presense of markers:</p>
<pre lang="matlab">
>> get(hLegendIconLine(1))  % Marker
    EdgeColorBinding: 'object'
       EdgeColorData: [4×1 uint8]
       EdgeColorType: 'truecolor'
    FaceColorBinding: 'object'
       FaceColorData: []
       FaceColorType: 'truecolor'
    HandleVisibility: 'on'
             HitTest: 'off'
               Layer: 'middle'
           LineWidth: 0.5
              Parent: [1×1 Group]
       PickableParts: 'visible'
                Size: 6
         SizeBinding: 'object'
               Style: 'circle'
          VertexData: [3×1 single]
       VertexIndices: []
             Visible: 'on'
</pre>
<p>An additional undocumented legend property that is of interest is <b>ItemTokenSize</b>. This is a 2-element numeric array specifying the minimal size of the legend entries&#8217; icon and label. By default <code>hLegend.ItemTokenSize == [30,18]</code>, but we can either expand or shrink the icons/labels by setting different values. For example:</p>
<pre lang="matlab">hLegend.ItemTokenSize == [10,1];  % shrink legend icons and labels</pre>
<p>Note that regardless of the amount that we specify, the actual amount that will be used will be such that all legend labels appear.<br />
Fun: try playing with negative values for the icon and the label and see what happens 🙂<br />
Have you come across any other interesting undocumented aspect of Matlab legends? If so, then please share it in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-customization">Plot legend customization</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/plot-legend-title" rel="bookmark" title="Plot legend title">Plot legend title </a> <small>Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" rel="bookmark" title="Plot line transparency and color gradient">Plot line transparency and color gradient </a> <small>Static and interpolated (gradient) colors and transparency can be set for plot lines in HG2. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/plot-legend-customization/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Auto-scale image colors</title>
		<link>https://undocumentedmatlab.com/articles/auto-scale-image-colors?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=auto-scale-image-colors</link>
					<comments>https://undocumentedmatlab.com/articles/auto-scale-image-colors#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 21 Feb 2018 18:06:23 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[Listener]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7334</guid>

					<description><![CDATA[<p>Images can be automatically color-scaled for maximum resolution, using the undocumented MarkedClean  event. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/auto-scale-image-colors">Auto-scale image colors</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/image-easter-egg" rel="bookmark" title="Image Easter egg">Image Easter egg </a> <small>The default image presented by Matlab's image function has a very interesting undocumented story....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2" rel="bookmark" title="Persisting transparent colors in HG2">Persisting transparent colors in HG2 </a> <small>We can set semi- and fully-transparent colors in HG2 for multiple graphic objects, but making these settings stick is non-trivial. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-cell-colors" rel="bookmark" title="Uitable cell colors">Uitable cell colors </a> <small>A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I deal extensively in image processing in one of my consulting projects. The images are such that most of the interesting features are found in the central portion of the image. However, the margins of the image contain z-values that, while not interesting from an operational point-of-view, cause the displayed image&#8217;s color-limits (axes <b>CLim</b> property) to go wild. An image is worth a thousand words, so check the following raw image (courtesy of Flightware, Inc.), displayed by the following simple script:</p>
<pre lang="matlab">hImage = imagesc(imageData); colormap(gray); colorbar;</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/baseline2_1.png" alt="Raw image with default Matlab CLim" title="Raw image with default Matlab CLim" width="400" height="299" /><figcaption class="wp-caption-text">Raw image with default Matlab CLim</figcaption></figure></center></p>
<h3 id="rescale">Rescaling the axes color-limits</h3>
<p>As you can see, this image is pretty useless for human-eye analysis. The reason is that while all of the interesting features in the central portion of the image have a z-value of ~-6, the few pixels in the margins that have a z-value of 350+ screw up the color limits and ruin the perceptual resolution (image contrast). We could of course start to guess (or <i><b>histogram</b></i> the z-values) to get the interesting color-limit range, and then manually set <code>hAxes.CLim</code> to get a much more usable image:</p>
<pre lang="matlab">hAxes = hImage.Parent; hAxes.CLim = [-7.5,-6];</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/static_1.png" alt="Raw image with a custom CLim" title="Raw image with a custom CLim" width="400" height="299" /><figcaption class="wp-caption-text">Raw image with a custom CLim</figcaption></figure></center></p>
<h3 id="autoscale">Auto-scaling the axes color-limits</h3>
<p>Since the z-values range and distribution changes between different images, it would be better to automatically scale the axes color-limits based on an analysis of the image. A very simple technique for doing this is to take the 5%,95% or 10%,90% percentiles of the data, clamping all outlier data pixels to the extreme colors. If you have the Stats Toolbox you can use the <i><b>prctile</b></i> function for this, but if not (or even if you do), here&#8217;s a very fast alternative that automatically scales the axes color limits based on the specified threshold (a fraction between 0-0.49):<br />
<span id="more-7334"></span></p>
<pre lang="matlab">
% Rescale axes CLim based on displayed image portion's CData
function rescaleAxesClim(hImage, threshold)
    % Get the displayed image portion's CData
    CData = hImage.CData;
    hAxes = hImage.Parent;
    XLim = fix(hAxes.XLim);
    YLim = fix(hAxes.YLim);
    rows = min(max(min(YLim):max(YLim),1),size(CData,1)); % visible portion
    cols = min(max(min(XLim):max(XLim),1),size(CData,2)); % visible portion
    CData = CData(unique(rows),unique(cols));
    CData = CData(:);  % it's easier to work with a 1d array
    % Find the CLims from this displayed portion's CData
    CData = sort(CData(~isnan(CData)));  % or use the Stat Toolbox's prctile()
    thresholdVals = [threshold, 1-threshold];
    thresholdIdxs = fix(numel(CData) .* thresholdVals);
    CLim = CData(thresholdIdxs);
    % Update the axes
    hAxes.CLim = CLim;
end
</pre>
<p>Note that a threshold of 0 uses the full color range, resulting in no <b>CLim</b> rescaling at all. At the other extreme, a threshold approaching 0.5 reduces the color-range to a single value, basically reducing the image to an unusable B/W (rather than grayscale) image. Different images might require different thresholds for optimal contrast. I believe that a good starting point for the threshold is a value of 0.10, which corresponds to the 10-90% range of <b>CData</b> values.</p>
<h3 id="dynamic">Dynamic auto-scaling of axes color-limits</h3>
<p>This is very nice for the initial image display, but if we zoom-in, or pan a sub-image around, or update the image in some way, we would need to repeat calling this <i>rescaleAxesClim()</i> function every time the displayed image portion changes, otherwise we might still get unusable images. For example, if we zoom into the image above, we will see that the color-limits that were useful for the full image are much less useful on the local sub-image scale. The first (left) image uses the static custom color limits [-7.5,-6] above (i.e., simply zooming-in on that image, without modifying <b>CLim</b> again); the second (right) image is the result of repeating the call to <i>rescaleAxesClim()</i>, which improves the image contrast:<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/static_4.png" alt="Zoomed-in image with a custom static CLim" title="Zoomed-in image with a custom static CLim" width="400" height="299" /><figcaption class="wp-caption-text">Zoomed-in image with a custom static CLim</figcaption></figure> <figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/dynamic_4.png" alt="Zoomed-in image with a re-applied custom CLim" title="Zoomed-in image with a re-applied custom CLim" width="400" height="299" /><figcaption class="wp-caption-text">Zoomed-in image with a re-applied custom CLim</figcaption></figure> </center><br />
We could in theory attach the <i>rescaleAxesClim()</i> function as a callback to the <i><b>zoom</b></i> and <i><b>pan</b></i> functions (that provide such callback hooks). However, we would still need to remember to manually call this function whenever we modify the image or its containing axes programmatically.<br />
A much simpler way is to attach our <i>rescaleAxesClim()</i> function as a callback to the image&#8217;s undocumented <a href="/articles/undocumented-hg2-graphics-events" target="_blank"><b>MarkedClean</b> event</a>:</p>
<pre lang="matlab">
% Instrument image: add a listener callback to rescale upon any image update
addlistener(hImage, 'MarkedClean', @(h,e)rescaleAxesClim(hImage,threshold));
</pre>
<p>In order to avoid callback recursion (potentially caused by modifying the axes <b>CLim</b> within the callback), we need to add a bit of code to the callback that prevents recursion/reentrancy (<a href="/articles/controlling-callback-re-entrancy" target="_blank">details</a>). Here&#8217;s one simple way to do this:</p>
<pre lang="matlab">
% Rescale axes CLim based on displayed image portion's CData
function rescaleAxesClim(hImage, threshold)
    % Check for callback reentrancy
    inCallback = getappdata(hImage, 'inCallback');
    if ~isempty(inCallback), return, end
    try
        setappdata(hImage, 'inCallback',1);  % prevent reentrancy
        % Get the displayed image portion's CData
        ...  (copied from above)
        % Update the axes
        hAx.CLim = CLim;
        drawnow; pause(0.001);  % finish all graphic updates before proceeding
    catch
    end
    setappdata(hImage, 'inCallback',[]);  % reenable this callback
end
</pre>
<p>The result of this dynamic automatic color-scaling can be seen below:<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/dynamic_animated.gif" alt="Zoomed-in image with dynamic CLim" title="Zoomed-in image with dynamic CLim" width="400" height="299" /><figcaption class="wp-caption-text">Zoomed-in image with dynamic CLim</figcaption></figure></center></p>
<h3 id="autoScaleImageCLim">autoScaleImageCLim utility</h3>
<p>I have created a small utility called <i><b>autoScaleImageCLim</b></i>, which includes all the above, and automatically sets the specified input image(s) to use auto color scaling. Feel free to download this utility from <a href="https://www.mathworks.com/matlabcentral/fileexchange/66148-autoscaleimageclim" rel="nofollow" target="_blank">the Matlab File Exchange</a>. Here are a few usage examples:</p>
<pre lang="matlab">
autoScaleImageCLim()           % auto-scale the current axes' image
autoScaleImageCLim(hImage,5)   % auto-scale image using 5%-95% CData limits
autoScaleImageCLim(hImage,.07) % auto-scale image using 7%-93% CData limits
</pre>
<p>(note that the <code>hImage</code> input parameter can be an array of image handles)<br />
Hopefully one day the so-useful <b>MarkedClean</b> event will become a documented and fully-supported event for all HG objects in Matlab, so that we won&#8217;t need to worry that it might not be supported by some future Matlab release&#8230;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/auto-scale-image-colors">Auto-scale image colors</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/image-easter-egg" rel="bookmark" title="Image Easter egg">Image Easter egg </a> <small>The default image presented by Matlab's image function has a very interesting undocumented story....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2" rel="bookmark" title="Persisting transparent colors in HG2">Persisting transparent colors in HG2 </a> <small>We can set semi- and fully-transparent colors in HG2 for multiple graphic objects, but making these settings stick is non-trivial. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-cell-colors" rel="bookmark" title="Uitable cell colors">Uitable cell colors </a> <small>A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/auto-scale-image-colors/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Adding custom properties to GUI objects</title>
		<link>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-custom-properties-to-gui-objects</link>
					<comments>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 15 Feb 2018 12:39:35 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7324</guid>

					<description><![CDATA[<p>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects">Adding custom properties to GUI objects</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</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/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab objects have numerous built-in properties (some of them publicly-accessible/documented and others not, but that&#8217;s a different story). For various purposes, it is sometimes useful to attach custom user-defined properties to such objects. While there was never a fully-documented way to do this, most users simply attached such properties as fields in the <b>UserData</b> property or the object&#8217;s [hidden] <b>ApplicationData</b> property (accessible via the documented <i><b>setappdata</b></i>/<i><b>getappdata</b></i> functions).<br />
An undocumented way to attach actual new user-defined properties to objects such as GUI handles or Java references has historically (in HG1, up to R2014a) been to use the undocumented <i><b>schema.prop</b></i> function, as I <a href="/articles/adding-dynamic-properties-to-graphic-handles" target="_blank">explained here</a>. As I wrote in that post, in HG2 (R2014b onward), we can use the fully-documented <a href="https://www.mathworks.com/help/matlab/ref/dynamicprops.addprop.html" rel="nofollow" target="_blank"><i><b>addprop</b></i> function</a> to add new custom properties (and methods) to such objects. What is still NOT documented, as far as I could tell, is that all of Matlab&#8217;s builtin handle graphics objects indirectly inherit the <code>dynamicprops</code> class, which allows this. The bottom line is that we can dynamically add custom properties in run-time to any HG object, without affecting any other object. In other words, the new properties will only be added to the handles that we specifically request, and not to any others.<br />
All this is important, because for some unexplained reason that escapes my understanding, MathWorks chose to seal its classes, thus preventing users to extend them with sub-classes that contain the new properties. So much frustration could have been solved if MathWorks would simply remove the <b>Sealed</b> class meta-property from its classes. Then again, I&#8217;d have less to blog about in that case&#8230;<br />
Anyway, why am I rehashing old news that I have already reported a few years ago?<br />
Well, first, because my experience has been that this little tidbit is [still] fairly unknown by Matlab developers. Secondly, I happened to run into a perfect usage example a short while ago that called for this solution: a <a href="https://stackoverflow.com/questions/48597836/matlab-figure-age" rel="nofollow" target="_blank">StackExchange user asked</a> whether it is possible to tell a GUI figure&#8217;s age, in other words the elapsed time since the figure was created. The simple answer would be to use <i><b>setappdata</b></i> with the creation date whenever we create a figure. However, a &#8220;cleaner&#8221; approach seems to be to create new read-only properties for the figure&#8217;s <b>CreationTime</b> and <b>Age</b>:<br />
<span id="more-7324"></span><br />
First, create a small Matlab function as follows, that attaches the CreationTime property to a figure:</p>
<pre lang="matlab">
function setCreationTime(hFig,varargin)
   hProp = addprop(hFig,'CreationTime');
   hFig.CreationTime = now;
   hProp.SetAccess = 'private';  % make property read-only after setting its initial value
   hProp = addprop(hFig,'Age');
   hProp.GetMethod = @(h,e) etime(datevec(hFig.CreationTime), clock);  % compute on-the-fly
   hProp.SetAccess = 'private';  % make property read-only
end
</pre>
<p>Now assign this function as the default CreateFcn callback function for all new figures from now on:</p>
<pre lang="matlab">
set(0,'DefaultFigureCreateFcn',@setCreationTime)
</pre>
<p>That&#8217;s it &#8211; you&#8217;re done! Whenever a new figure will be created from now on, it will have two custom read-only properties: <b>CreationTime</b> and <b>Age</b>.<br />
For example:</p>
<pre lang="matlab">
>> newFig = figure;
>> newFig.CreationTime
ans =
      737096.613706748
>> ageInDays = now - newFig.CreationTime
ageInDays =
       0.0162507836846635
>> ageDuration = duration(ageInDays*24,0,0)
ageDuration =
  duration
   00:23:24
>> ageString = datestr(ageInDays, 'HH:MM:SS.FFF')
ageString =
    '00:23:24.068'
>> ageInSecs = newFig.Age
ageInSecs =
       1404.06771035492
</pre>
<p>Note that an alternative way to set the computed property <b>Age</b> would have been to set its value to be an anonymous function, but this would have necessitated invoking it with parenthesis (as in: <code>ageInSecs = newFig.Age()</code>). By setting the property&#8217;s <b>GetMethod</b> meta-property we avoid this need.<br />
Keen readers will have noticed that the mechanism that I outlined above for the <b>Age</b> property/method can also be used to add custom user methods. For example, we can create a new custom property named <b>refresh</b> that would be read-only and have a <b>GetMethod</b> which is the function handle of the function that refreshes the object in some way.<br />
Do you have any special uses for custom user-defined properties/methods in your program? or perhaps you have a use-case that might show MathWorks why sub-classing the built-in classes might improve your work? if so, then please place a comment about it below. If enough users show MathWorks why this is important, then maybe it will be fixed in some future release.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects">Adding custom properties to GUI objects</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</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/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing axes tick labels</title>
		<link>https://undocumentedmatlab.com/articles/customizing-axes-tick-labels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-axes-tick-labels</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-axes-tick-labels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 24 Jan 2018 13:38:26 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7304</guid>

					<description><![CDATA[<p>Multiple customizations can be applied to tick labels. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels">Customizing axes tick labels</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/setting-axes-tick-labels-format" rel="bookmark" title="Setting axes tick labels format">Setting axes tick labels format </a> <small>Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="/articles/customizing-histogram-plots" target="_blank">last week&#8217;s post</a>, I discussed various ways to customize bar/histogram plots, including customization of the tick labels. While some of the customizations that I discussed indeed rely on undocumented properties/features, many Matlab users are not aware that tick labels can be individually customized, and that this is a <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.axis.axes-properties.html#property_d119e51283" rel="nofollow" target="_blank">fully documented/supported functionality</a>. This relies on the fact that the default axes <b>TickLabelInterpreter</b> property value is <code>'tex'</code>, which supports a wide range of font customizations, individually for each label. This includes any combination of symbols, superscript, subscript, bold, italic, slanted, face-name, font-size and color &#8211; even intermixed within a single label. Since tex is the default interpreter, we don&#8217;t need any special preparation &#8211; simply set the relevant <b>X/Y/ZTickLabel</b> string to include the relevant tex markup.<br />
To illustrate this, have a look at the following <a href="https://stackoverflow.com/a/46181211/233829" rel="nofollow" target="_blank">excellent answer</a> by user Ubi on Stack Overflow:<br />
<figure style="width: 450px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://i.stack.imgur.com/3vjhD.png" alt="Axes with Tex-customized tick labels" title="Axes with Tex-customized tick labels" width="450" height="300" /><figcaption class="wp-caption-text">Axes with Tex-customized tick labels</figcaption></figure></p>
<pre lang="matlab">
plot(1:10, rand(1,10))
ax = gca;
% Simply color an XTickLabel
ax.XTickLabel{3} = ['\color{red}' ax.XTickLabel{3}];
% Use TeX symbols
ax.XTickLabel{4} = '\color{blue} \uparrow';
% Use multiple colors in one XTickLabel
ax.XTickLabel{5} = '\color[rgb]{0,1,0}green\color{orange}?';
% Color YTickLabels with colormap
nColors = numel(ax.YTickLabel);
cm = jet(nColors);
for i = 1:nColors
    ax.YTickLabel{i} = sprintf('\\color[rgb]{%f,%f,%f}%s', cm(i,:), ax.YTickLabel{i});
end
</pre>
<p>In addition to <code>'tex'</code>, we can also set the axes object&#8217;s <b>TickLabelInterpreter</b> to <code>'latex'</code> for a Latex interpreter, or <code>'none'</code> if we want to use no string interpretation at all.<br />
As I showed in <a href="/articles/customizing-histogram-plots" target="_blank">last week&#8217;s post</a>, we can control the gap between the tick labels and the axle line, using the Ruler object&#8217;s undocumented <b>TickLabelGapOffset, TickLabelGapMultiplier</b> properties.<br />
Also, as I explained in other posts (<a href="/articles/customizing-axes-part-5-origin-crossover-and-labels" target="_blank">here</a> and <a href="/articles/customizing-axes-rulers#Exponent" target="_blank">here</a>), we can also control the display of the secondary axle label (typically exponent or units) using the Ruler&#8217;s similarly-undocumented <b>SecondaryLabel</b> property. Note that the related Ruler&#8217;s <b>Exponent</b> property is <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.axis.decorator.numericruler-properties.html" rel="nofollow" target="_blank">documented/supported</a>, but simply sets a basic exponent label (e.g., <code>'\times10^{6}'</code> when <b>Exponent</b>==6) &#8211; to set a custom label string (e.g., <code>'\it\color{gray}Millions'</code>), or to modify its other properties (position, alignment etc.), we should use <b>SecondaryLabel</b>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels">Customizing axes tick labels</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/setting-axes-tick-labels-format" rel="bookmark" title="Setting axes tick labels format">Setting axes tick labels format </a> <small>Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-axes-tick-labels/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing histogram plots</title>
		<link>https://undocumentedmatlab.com/articles/customizing-histogram-plots?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-histogram-plots</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-histogram-plots#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 17 Jan 2018 20:41:15 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7292</guid>

					<description><![CDATA[<p>Basic bar charts and histogram plots can be customized in important aspects. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-histogram-plots">Customizing histogram plots</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-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>Matlab contour labels' color and font can easily be customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Earlier today, I was given the task of displaying a histogram plot of a list of values. In today&#8217;s post, I will walk through a few customizations that can be done to bar plots and histograms in order to achieve the desired results.<br />
We start by binning the raw data into pre-selected bins. This can easily be done using the builtin <i><b>histc</b></i> (deprecated) or <i><b>histcounts</b></i> functions. We can then use the <a href="https://www.mathworks.com/help/matlab/ref/bar.html" rel="nofollow" target="_blank"><i><b>bar</b></i> function</a> to plot the results:</p>
<pre lang="matlab">
[binCounts, binEdges] = histcounts(data);
hBars = bar(hAxes, binEdges(1:end-1), binCounts);
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram1.png" alt="Basic histogram bar plot" title="Basic histogram bar plot" width="400" height="180" /><figcaption class="wp-caption-text">Basic histogram bar plot</figcaption></figure></center><br />
Let&#8217;s improve the appearance: <span id="more-7292"></span>In my specific case, the data was financial return (percentage) values, so let&#8217;s modify the x-label format accordingly and display a title. To make the labels and title more legible, we decrease the axes <b>FontSize</b> to 8 and remove the axes box:</p>
<pre lang="matlab">
hAxes = hBar.Parent;
xtickformat(hAxes, '%g%%');
title(hAxes, 'Distribution of total returns (monthly %)');
set(hAxes, 'FontSize',8, 'Box','off')
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram2.png" alt="Improved histogram bar plot" title="Improved histogram bar plot" width="400" height="180" /><figcaption class="wp-caption-text">Improved histogram bar plot</figcaption></figure></center><br />
So far nothing undocumented. Note that the <i><b>xtickformat/ytickformat</b></i> functions were only introduced in R2016b &#8211; for earlier Matlab releases <a href="/articles/setting-axes-tick-labels-format" target="_blank">see this post</a> (which does rely on undocumented aspects).<br />
Now, let&#8217;s use a couple of undocumented properties: to remove the excess white-space margin around the axes we&#8217;ll set the axes&#8217; <a href="/articles/axes-looseinset-property" target="_blank"><b>LooseInset</b> property</a>, and to remove the annoying white space between the tick labels and the X-axis we&#8217;ll set the <b>XRuler</b>&#8216;s <b>TickLabelGapOffset</b> property to -2 (default: +2):</p>
<pre lang="matlab">
set(hAxes, 'LooseInset',[0,0,0,0]);    % default = [.13,.11,.095,.075]
hAxes.XRuler.TickLabelGapOffset = -2;  % default = +2
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram3.png" alt="Even better histogram bar plot" title="Even better histogram bar plot" width="400" height="180" /><figcaption class="wp-caption-text">Even better histogram bar plot</figcaption></figure></center><br />
Note that I used the undocumented axes <b>XRuler</b> property instead of the axes&#8217; documented <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.axis.axes-properties.html#prop_XAxis" rel="nofollow" target="_blank"><b>XAxis</b> property</a>, because <b>XAxis</b> is only available since R2015b, whereas <b>XRuler</b> (which points to the exact same object as <b>XAxis</b>) exists ever since R2014b, and so is better from a backward-compatibility standpoint. In either case, the ruler&#8217;s <b>TickLabelGapOffset</b> property is undocumented. Note that the ruler also contains another associated and undocumented <b>TickLabelGapMultiplier</b> property (default: 0.2), which I have not modified in this case.<br />
Now let&#8217;s take a look at the bin labels: The problem with the bar plot above is that it&#8217;s not intuitively clear whether the bin for &#8220;5%&#8221;, for example, includes data between 4.5-5.5 or between 5.0-6.0 (which is the correct answer). It would be nicer if the labels were matched to the actual bin edges. There are 3 basic ways to fix this:</p>
<ol>
<li>We could modify the bar plot axes tick values and labels, in essence &#8220;cheating&#8221; by moving the tick labels half a bin leftward of their tick values (don&#8217;t forget to add the extra tick label on the right):
<pre lang="matlab">
hAxes.XTick(end+1) = hAxes.XTick(end) + 1;  % extra tick label on the right
labels = hAxes.XTickLabels;       % preserve tick labels for later use below
hAxes.XTick = hAxes.XTick - 0.5;  % move tick labels 1/2 bin leftward
hAxes.XTickLabel = labels;        % restore pre-saved tick labels
hAxes.XLim = hAxes.XLim - 0.5;    % ...and align the XLim
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram4.png" alt="Improved labels" title="Improved labels" width="400" height="180" /><figcaption class="wp-caption-text">Improved labels</figcaption></figure></center>
</li>
<li>We could use the <i><b>bar</b></i> function&#8217;s optional <code>'histc'</code> flag, in order to display the bars in histogram mode. The problem in histogram mode is that while the labels are now placed correctly, the bars touch each other &#8211; I personally find distinct bars that are separated by a small gap easier to understand.
<pre lang="matlab">
hBars = bar(..., 'histc');
% [snip] - same customizations to hAxes as done above
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram5.png" alt="Basic histogram plot" title="Basic histogram plot" width="400" height="180" /><figcaption class="wp-caption-text">Basic histogram plot</figcaption></figure></center><br />
With the original bar chart we could use the built-in <b>BarWidth</b> to set the bar/gap width (default: 0.8 meaning a 10% gap on either side of the bar). Unfortunately, calling <i><b>bar</b></i> with <code>'hist'</code> or <code>'histc'</code> (i.e. histogram mode) results in a <code>Patch</code> (not <code>Bar</code>) object, and patches do not have a <b>BarWidth</b> property. However, we can modify the resulting patch vertices in order to achieve the same effect:</p>
<pre lang="matlab">
% Modify the patch vertices (5 vertices per bar, row-based)
hBars.Vertices(:,1) = hBars.Vertices(:,1) + 0.1;
hBars.Vertices(4:5:end,1) = hBars.Vertices(4:5:end,1) - 0.2;
hBars.Vertices(5:5:end,1) = hBars.Vertices(5:5:end,1) - 0.2;
% Align the bars & labels at the center of the axes
hAxes.XLim = hAxes.XLim + 0.5;
</pre>
<p>This now looks the same as option #1 above, except that the top-level handle is a <code>Patch</code> (not <code>Bar</code>) object. For various additional customizations, either <code>Patch</code> or <code>Bar</code> might be preferable, so you have a choice.<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram4.png" alt="Improved histogram plot" title="Improved histogram plot" width="400" height="180" /><figcaption class="wp-caption-text">Improved histogram plot</figcaption></figure></center>
</li>
<li>Lastly, we could have used the builtin <a href="https://www.mathworks.com/help/matlab/ref/histogram.html" rel="nofollow" target="_blank"><i><b>histogram</b></i> function</a> instead of <i><b>bar</b></i>. This function also displays a plot with touching bars, as above, using <code>Quadrilateral</code> objects (a close relative of <code>Patch</code>). The solution here is very similar to option #2 above, but we need to dig a bit harder to modify the patch faces, since their vertices is not exposed as a public property of the <code>Histogram</code> object. To modify the vertices, we first get the private <b>Face</b> property (<a href="/articles/accessing-private-object-properties" target="_blank">explanation</a>), and then modify its vertices, keeping in mind that in this specific case the bars have 4 vertices per bar and a different vertices matrix orientation:
<pre lang="matlab">
hBars = histogram(data, 'FaceAlpha',1.0, 'EdgeColor','none');
% [snip] - same customizations to hAxes as done above
% Get access to *ALL* the object's properties
oldWarn = warning('off','MATLAB:structOnObject');
warning off MATLAB:hg:EraseModeIgnored
hBarsStruct = struct(hBars);
warning(oldWarn);
% Modify the patch vertices (4 vertices per bar, column-based)
drawnow;  % this is important, won't work without this!
hFace = hBarsStruct.Face;  % a Quadrilateral object (matlab.graphics.primitive.world.Quadrilateral)
hFace.VertexData(1,:) = hFace.VertexData(1,:) + 0.1;
hFace.VertexData(1,3:4:end) = hFace.VertexData(1,3:4:end) - 0.2;
hFace.VertexData(1,4:4:end) = hFace.VertexData(1,4:4:end) - 0.2;
</pre>
</ol>
<p>In conclusion, there are many different ways to improve the appearance of charts in Matlab. Even if at first glance it may seem that some visualization function does not have the requested customization property or feature, a little digging will often find either a relevant undocumented property, or an internal object whose properties could be modified. If you need assistance with customizing your charts for improved functionality and appearance, then consider contacting me for a <a href="/consulting" target="_blank">consulting session</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-histogram-plots">Customizing histogram plots</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-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>Matlab contour labels' color and font can easily be customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-histogram-plots/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>PlotEdit context-menu customization</title>
		<link>https://undocumentedmatlab.com/articles/plotedit-context-menu-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=plotedit-context-menu-customization</link>
					<comments>https://undocumentedmatlab.com/articles/plotedit-context-menu-customization#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Dec 2017 12:57:14 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7236</guid>

					<description><![CDATA[<p>A combination of Matlab and Java Robot commands to automate a certain animation can be used when we cannot access underlying GUI/graphics code. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plotedit-context-menu-customization">PlotEdit context-menu customization</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-context-menu-to-uitree" rel="bookmark" title="Adding a context-menu to a uitree">Adding a context-menu to a uitree </a> <small>uitree is an undocumented Matlab function, which does not easily enable setting a context-menu. Here's how to do it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/context-sensitive-help" rel="bookmark" title="Context-Sensitive Help">Context-Sensitive Help </a> <small>Matlab has a hidden/unsupported built-in mechanism for easy implementation of context-sensitive help...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-workspace-context-menu" rel="bookmark" title="Customizing Workspace context-menu">Customizing Workspace context-menu </a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-customization-report" rel="bookmark" title="Uitable customization report">Uitable customization report </a> <small>Matlab's uitable can be customized in many different ways. A detailed report explains how. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week, <a href="https://www.mathworks.com/matlabcentral/answers/370545-prompt-user-before-clearing-axis-when-using-the-clear-axes-context-menu" rel="nofollow" target="_blank">a Matlab user asked</a> whether it is possible to customize the context (right-click) menu that is presented in plot-edit mode. This menu is displayed by clicking the plot-edit (arrow) icon on the standard Matlab figure toolbar, then right-clicking any graphic/GUI element in the figure. Unfortunately, it seems that this context menu is only created the first time that a user right-clicks in plot-edit mode &#8211; it is not accessible before then, and so it seems impossible to customize the menu before it is presented to the user the first time.<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized plot-edit context-menu" src="https://undocumentedmatlab.com/images/PlotEdit_context_menu.png" title="Customized plot-edit context-menu" width="400" height="337" /><figcaption class="wp-caption-text">Customized plot-edit context-menu</figcaption></figure></center><br />
A few workarounds <a href="https://www.mathworks.com/matlabcentral/answers/370545-prompt-user-before-clearing-axis-when-using-the-clear-axes-context-menu" rel="nofollow" target="_blank">were suggested</a> to the original poster and you are most welcome to review them. There is also some discussion about the technical reasons that none of the &#8220;standard&#8221; ways of finding and modifying menu items fail in this case.<br />
In today&#8217;s post I wish to repost my solution, in the hope that it might help other users in similar cases.<br />
My solution is basically this:<br />
<span id="more-7236"></span></p>
<ol>
<li>First, enter plot-edit mode programmatically using the <i><b>plotedit</b></i> function</li>
<li>Next, move the mouse to the screen location of the relevant figure component (e.g. axes). This can be done in several different ways (the root object&#8217;s <b>PointerLocation</b> property, the <a href="/articles/undocumented-mouse-pointer-functions" target="_blank">moveptr</a> function, or <a href="/articles/gui-automation-robot" target="_blank"><code>java.awt.Robot.<i>mouseMove()</i></code></a> method).</li>
<li>Next, automate a mouse right-click using the built in <a href="https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html" rel="nofollow" target="_blank"><code>java.awt.Robot</code></a> class (as <a href="/articles/gui-automation-robot" target="_blank">discussed in this blog</a> back in 2010)</li>
<li>Next, locate the relevant context-menu item and modify its label, callback or any of its other properties</li>
<li>Next, dismiss the context-menu by simulating a follow-on right-click using the same <code>Robot</code> object</li>
<li>Finally, exit plot-edit mode and return the mouse pointer to its original location</li>
</ol>
<pre lang="matlab">
% Create an initial figure / axes for demostration purpose
fig = figure('MenuBar','none','Toolbar','figure');
plot(1:5); drawnow;
% Enter plot-edit mode temporarily
plotedit(fig,'on'); drawnow
% Preserve the current mouse pointer location
oldPos = get(0,'PointerLocation');
% Move the mouse pointer to within the axes boundary
% ref: https://undocumentedmatlab.com/articles/undocumented-mouse-pointer-functions
figPos = getpixelposition(fig);   % figure position
axPos  = getpixelposition(gca,1); % axes position
figure(fig);  % ensure that the figure is in focus
newPos = figPos(1:2) + axPos(1:2) + axPos(3:4)/4;  % new pointer position
set(0,'PointerLocation',newPos);  % alternatives: moveptr(), java.awt.Robot.mouseMove()
% Simulate a right-click using Java robot
% ref: https://undocumentedmatlab.com/articles/gui-automation-robot
robot = java.awt.Robot;
robot.mousePress  (java.awt.event.InputEvent.BUTTON3_MASK); pause(0.1)
robot.mouseRelease(java.awt.event.InputEvent.BUTTON3_MASK); pause(0.1)
% Modify the <clear-axes> menu item
hMenuItem = findall(fig,'Label','Clear Axes');
if ~isempty(hMenuItem)
   label = '<html><b><i><font color="blue">Undocumented Matlab';
   callback = 'web(''https://undocumentedmatlab.com'',''-browser'');';
   set(hMenuItem, 'Label',label, 'Callback',callback);
end
% Hide the context menu by simulating a left-click slightly offset
set(0,'PointerLocation',newPos+[-2,2]);  % 2 pixels up-and-left
pause(0.1)
robot.mousePress  (java.awt.event.InputEvent.BUTTON1_MASK); pause(0.1)
robot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK); pause(0.1)
% Exit plot-edit mode
plotedit(fig,'off'); drawnow
% Restore the mouse pointer to its previous location
set(0,'PointerLocation',oldPos);
</pre>
<p>In this code, I sprinkled a few <i><b>pause</b></i>s at several locations, to ensure that everything has time to fully render. Different pause values, or perhaps no pause at all, may be needed on your specific system.<br />
Modifying the default context-menu shown in plot-edit mode may perhaps be an uncommon use-case. But the technique that I demonstrated above &#8211; of using a combination of Matlab and Java <code>Robot</code> commands to automate a certain animation &#8211; can well be used in many other use-cases where we cannot easily access the underlying code. For example, when the internal code is encoded/encrypted, or when a certain functionality (such as the plot-edit context-menu) is created on-the-fly.<br />
If you have encountered a similar use-case where such automated animations can be used effectively, please add a comment below. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plotedit-context-menu-customization">PlotEdit context-menu customization</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-context-menu-to-uitree" rel="bookmark" title="Adding a context-menu to a uitree">Adding a context-menu to a uitree </a> <small>uitree is an undocumented Matlab function, which does not easily enable setting a context-menu. Here's how to do it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/context-sensitive-help" rel="bookmark" title="Context-Sensitive Help">Context-Sensitive Help </a> <small>Matlab has a hidden/unsupported built-in mechanism for easy implementation of context-sensitive help...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-workspace-context-menu" rel="bookmark" title="Customizing Workspace context-menu">Customizing Workspace context-menu </a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-customization-report" rel="bookmark" title="Uitable customization report">Uitable customization report </a> <small>Matlab's uitable can be customized in many different ways. A detailed report explains how. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/plotedit-context-menu-customization/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing contour plots part 2</title>
		<link>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-contour-plots-part2</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 12 Nov 2017 11:03:37 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7149</guid>

					<description><![CDATA[<p>Matlab contour labels' color and font can easily be customized. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2">Customizing contour plots part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-histogram-plots" rel="bookmark" title="Customizing histogram plots">Customizing histogram plots </a> <small>Basic bar charts and histogram plots can be customized in important aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few weeks ago a user posted a question on Matlab&#8217;s Answers forum, asking whether it is possible to <a href="https://www.mathworks.com/matlabcentral/answers/363059-how-do-i-label-a-contour-plot-in-the-same-colors-as-the-contour-lines" rel="nofollow" target="_blank">display contour labels in the same color as their corresponding contour lines</a>. In today&#8217;s post I&#8217;ll provide some insight that may assist users with similar customizations in other plot types.<br />
Matlab does not provide, for reasons that escape my limited understanding, documented access to the contour plot&#8217;s component primitives, namely its contour lines, labels and patch faces. Luckily however, these handles are accessible (in HG2, i.e. R2014b onward) via undocumented hidden properties aptly named <b>EdgePrims</b>, <b>TextPrims</b> and <b>FacePrims</b>, as I explained in a previous post about <a href="/articles/customizing-contour-plots" target="_blank">contour plots customization</a>, two years ago.<br />
Let&#8217;s start with a simple contour plot of the <i><b>peaks</b></i> function:</p>
<pre lang="matlab">
[X,Y,Z] = peaks;
[C,hContour] = contour(X,Y,Z, 'ShowText','on', 'LevelStep',1);
</pre>
<p>The result is the screenshot on the left:<br />
<center><figure style="width: 454px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Standard Matlab contour labels" src="https://undocumentedmatlab.com/images/contour_labels_1b.png" title="Standard Matlab contour labels" width="454" height="367" /><figcaption class="wp-caption-text">Standard Matlab contour labels</figcaption></figure> &nbsp; <figure style="width: 454px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized Matlab contour labels" src="https://undocumentedmatlab.com/images/contour_labels_2b.png" title="Customized Matlab contour labels" width="454" height="367" /><figcaption class="wp-caption-text">Customized Matlab contour labels</figcaption></figure></center><br />
In order to update the label colors (to get the screenshot on the right), we create a short <code>updateContours</code> function that updates the <b>TextPrims</b> color to their corresponding <b>EdgePrims</b> color:<br />
<span id="more-7149"></span></p>
<h3 id="updateContours">The updateContours() function</h3>
<pre lang="matlab">
function updateContours(hContour)
    % Update the text label colors
    drawnow  % very important!
    levels = hContour.LevelList;
    labels = hContour.TextPrims;  % undocumented/unsupported
    lines  = hContour.EdgePrims;  % undocumented/unsupported
    for idx = 1 : numel(labels)
        labelValue = str2double(labels(idx).String);
        lineIdx = find(abs(levels-labelValue)<10*eps, 1);  % avoid FP errors using eps
        labels(idx).ColorData = lines(lineIdx).ColorData;  % update the label color
        %labels(idx).Font.Size = 8;                        % update the label font size
    end
    drawnow  % optional
end
</pre>
<p>Note that in this function we don't directly equate the numeric label values to the contour levels' values: this would work well for integer values but would fail with floating-point ones. Instead I used a very small <code>10*eps</code> tolerance in the numeric comparison.<br />
Also note that I was careful to call <i><b>drawnow</b></i> at the top of the update function, in order to ensure that <b>EdgePrims</b> and <b>TextPrims</b> are updated when the function is called (this might not be the case before the call to <i><b>drawnow</b></i>). The final <i><b>drawnow</b></i> at the end of the function is optional: it is meant to reduce the flicker caused by the changing label colors, but it can be removed to improve the rendering performance in case of rapidly-changing contour plots.<br />
Finally, note that I added a commented line that shows we can modify other label properties (in this case, the font size from 10 to 8). Feel free to experiment with other label properties.</p>
<h3 id="summary">Putting it all together</h3>
<p>The final stage is to call our new <code>updateContours</code> function directly, immediately after creating the contour plot. We also want to call <code>updateContours</code> asynchronously whenever the contour is redrawn, for example, upon a zoom/pan event, or when one of the relevant contour properties (e.g., <b>LevelStep</b> or <b>*Data</b>) changes. To do this, we add a callback listener to the contour object's [undocumented] <a href="/articles/undocumented-hg2-graphics-events" target="_blank"><b>MarkedClean</b> event</a> that reruns our <code>updateContours</code> function:</p>
<pre lang="matlab">
[X,Y,Z] = peaks;
[C,hContour] = contour(X,Y,Z, 'ShowText','on', 'LevelStep',1);
% Update the contours immediately, and also whenever the contour is redrawn
updateContours(hContour);
addlistener(hContour, 'MarkedClean', @(h,e)updateContours(hContour));
</pre>
<h3 id="">Contour level values</h3>
<p>As noted in my <a href="/articles/customizing-contour-plots-part2#comment-416543">comment reply</a> below, the contour lines (hContour.<b>EdgePrims</b>) correspond to the contour levels (hContour.<b>LevelList</b>).<br />
For example, to make all negative contour lines dotted, you can do the following:</p>
<pre lang="matlab">
[C,hContour] = contour(peaks, 'ShowText','on', 'LevelStep',1); drawnow
set(hContour.EdgePrims(hContour.LevelList<0), 'LineStyle', 'dotted');
</pre>
<p><center><figure style="width: 455px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized Matlab contour lines" src="https://undocumentedmatlab.com/images/contour_labels_3.png" title="Customized Matlab contour lines" width="455" height="363" /><figcaption class="wp-caption-text">Customized Matlab contour lines</figcaption></figure></center></p>
<h3 id="future">Prediction about forward compatibility</h3>
<p>As I noted on my <a href="/articles/customizing-contour-plots" target="_blank">previous post on contour plot customization</a>, I am marking this article as "<a target="_blank" href="/articles/category/presumed-future-risk/high-risk-of-breaking-in-future-versions">High risk of breaking in future Matlab versions</a>", not because of the basic functionality (being important enough I don't presume it will go away anytime soon) but because of the property names: <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> don't seem to be very user-friendly property names. So far MathWorks has been very diligent in making its object properties have meaningful names, and so I assume that when the time comes to expose these properties, they will be renamed (perhaps to <b>TextHandles</b>, <b>EdgeHandles</b> and <b>FaceHandles</b>, or perhaps <b>LabelHandles</b>, <b>LineHandles</b> and <b>FillHandles</b>). For this reason, even if you find out in some future Matlab release that <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> don't exist, perhaps they still exist and simply have different names. Note that these properties have not changed their names or functionality in the past 3 years, so while it could well happen next year, it could also remain unchanged for many years to come. The exact same thing can be said for the <b>MarkedClean</b> event.</p>
<h3 id="consulting">Professional assistance anyone?</h3>
<p>As shown by this and many other posts on this site, a polished interface and functionality is often composed of small professional touches, many of which are not exposed in the official Matlab documentation for various reasons. So if you need top-quality professional appearance/functionality in your Matlab program, or maybe just a Matlab program that is dependable, robust and highly-performant, consider employing my <a href="/consulting" target="_blank">consulting services</a>. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2">Customizing contour plots part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-histogram-plots" rel="bookmark" title="Customizing histogram plots">Customizing histogram plots </a> <small>Basic bar charts and histogram plots can be customized in important aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2/feed</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>Tips for accelerating Matlab performance</title>
		<link>https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=tips-for-accelerating-matlab-performance</link>
					<comments>https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 05 Oct 2017 18:25:06 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Mathworks.com]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7099</guid>

					<description><![CDATA[<p>My article on "Tips for Accelerating MATLAB Performance" was recently featured in the September 2017 Matlab newsletter digest. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance">Tips for accelerating Matlab 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/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/new-book-accelerating-matlab-performance" rel="bookmark" title="New book: Accelerating MATLAB Performance">New book: Accelerating MATLAB Performance </a> <small>Accelerating MATLAB Performance (ISBN 9781482211290) is a book dedicated to improving Matlab performance (speed). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/a-few-parfor-tips" rel="bookmark" title="A few parfor tips">A few parfor tips </a> <small>The parfor (parallel for) loops can be made faster using a few simple tips. ...</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I&#8217;m proud to report that MathWorks has recently posted my article &#8220;<a href="https://www.mathworks.com/company/newsletters/articles/tips-for-accelerating-matlab-performance.html" rel="nofollow" target="_blank"><i>Tips for Accelerating MATLAB Performance</i></a>&#8221; in their latest newsletter digest (September 2017). This article is an updated and expanded version of <a href="/articles/some-performance-tuning-tips" target="_blank">my post</a> about consulting work that I did for the <a href="http://summit.fas.harvard.edu" rel="nofollow" target="_blank">Crustal Dynamics Research Group</a> at Harvard University, where I helped speed-up a complex Matlab-based GUI by a factor of 50-500 (depending on the specific feature). You can read the full <a href="/articles/some-performance-tuning-tips" target="_blank">detailed technical article</a> here.<br />
<center><figure style="width: 600px" class="wp-caption aligncenter"><a target="_blank" href="/images/ResultManagerGUI.gif"><img loading="lazy" decoding="async" alt="Crustal dynamics visualization GUI" src="https://undocumentedmatlab.com/images/ResultManagerGUI_600x401.gif" title="Crustal dynamics visualization GUI" width="600" height="401" /></a><figcaption class="wp-caption-text">Crustal dynamics visualization GUI</figcaption></figure></center><span id="more-7099"></span><br />
Featuring an article on the official newsletter by a non-MathWorker is rare. Doing this with someone like myself who has a reputation for undocumented aspects, and a consultancy business that potentially competes with theirs, is certainly not obvious. I take this to be a sign that despite the possible drawbacks of publishing my article, MathWorks felt that it provided enough value to the Matlab user community to merit the risk. I applaud MathWorks for this, and thank them for the opportunity of being featured in their official newsletter and conferences. I do not take it for granted in the least.<br />
The newsletter article provides multiple ideas of improving the run-time performance for file I/O and graphics. Many additional techniques for improving Matlab&#8217;s performance can be found under the <a href="/articles/tag/performance" target="_blank">Performance tag</a> in this blog, as well as in my book &#8220;<a href="/books/matlab-performance" target="_blank"><b>Accelerating MATLAB Performance</b></a>&#8221; (CRC Press, 2014, ISBN 978-1482211290).<br />
<!--
Next week I will present live online webinars about various ways to improve Matlab's run-time performance:


<ul>
	

<li>Oct 9, 2017 (Mon) - <a target="_blank" href="/courses/Matlab_Performance_Tuning_1_Webinar.pdf">Matlab performance tuning part 1</a> - $295 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&currency_code=USD&business=octahedron.ltd@gmail.com&quantity=1&amount=295&item_name=Matlab+performance+1+webinar" rel="nofollow" target="_blank">buy</a>)</li>


	

<li>Oct 10, 2017 (Tue) - <a target="_blank" href="/courses/Matlab_Performance_Tuning_2_Webinar.pdf">Matlab performance tuning part 2</a> - $295 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&currency_code=USD&business=octahedron.ltd@gmail.com&quantity=1&amount=295&item_name=Matlab+performance+2+webinar" rel="nofollow" target="_blank">buy</a>)
 &nbsp;&nbsp;&nbsp; ==> or buy both Matlab performance tuning webinars for only $495 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&currency_code=USD&business=octahedron.ltd@gmail.com&quantity=1&amount=495&item_name=Matlab+performance+webinars" rel="nofollow" target="_blank">buy</a>)</li>


</ul>


These live webinars will be 3.5 hours long, starting at 10am EDT (7am PDT, 3pm UK, 4pm CET, 7:30pm IST, <a href="https://www.google.com/search?q=9am+edt+to+my+time" rel="nofollow" target="_blank">time in your local timezone</a>), with a short break in the middle. The presentations content will be based on onsite training courses that I presented at multiple client locations (<a href="/training#onsite" target="_blank">details</a>). A recording of the webinars will be available for anyone who cannot join the live events.
--><br />
I am offering a couple of webinars about various ways to improve Matlab&#8217;s run-time performance:</p>
<ul>
<li><a target="_blank" href="/courses/Matlab_Performance_Tuning_1_Webinar.pdf">Matlab performance tuning part 1</a> (3:39 hours, <a target="_blank" href="/courses/Matlab_Performance_Tuning_1_Webinar.pdf">syllabus</a>) &#8211; $195 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=octahedron.ltd@gmail.com&#038;quantity=1&#038;amount=195&#038;item_name=Matlab+performance+1+webinar" rel="nofollow" target="_blank">buy</a>)</li>
<li><a target="_blank" href="/courses/Matlab_Performance_Tuning_2_Webinar.pdf">Matlab performance tuning part 2</a> (3:43 hours, <a target="_blank" href="/courses/Matlab_Performance_Tuning_2_Webinar.pdf">syllabus</a>) &#8211; $195 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=octahedron.ltd@gmail.com&#038;quantity=1&#038;amount=195&#038;item_name=Matlab+performance+2+webinar" rel="nofollow" target="_blank">buy</a>)<br />
 &nbsp;&nbsp;&nbsp; ==> or buy both Matlab performance tuning webinars for only $345 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=octahedron.ltd@gmail.com&#038;quantity=1&#038;amount=345&#038;item_name=Matlab+performance+webinars" rel="nofollow" target="_blank">buy</a>)</li>
</ul>
<p>Both the webinar videos and their corresponding slide-decks are available for download. The webinars content is based on onsite training courses that I presented at multiple client locations (<a href="/training#onsite" target="_blank">details</a>).<br />
<a href="mailto: altmany @gmail.com?subject=Matlab webinars&#038;body=Hi Yair, &#038;cc=;&#038;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab webinars&#038;body=Hi Yair, '); return false;"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/email-icon.png" width="32" height="22" alt="" style="vertical-align:middle;border:0"/>&nbsp;Email me</a> if you would like additional information on the webinars or my consulting, or to inquire regarding an onsite training course.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance">Tips for accelerating Matlab 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/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/new-book-accelerating-matlab-performance" rel="bookmark" title="New book: Accelerating MATLAB Performance">New book: Accelerating MATLAB Performance </a> <small>Accelerating MATLAB Performance (ISBN 9781482211290) is a book dedicated to improving Matlab performance (speed). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/a-few-parfor-tips" rel="bookmark" title="A few parfor tips">A few parfor tips </a> <small>The parfor (parallel for) loops can be made faster using a few simple tips. ...</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/tips-for-accelerating-matlab-performance/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
