<?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>Hidden property &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/category/hidden-property/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 13 Mar 2019 11:05:14 +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>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 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>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 fetchpriority="high" 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>MathWorks-solicited Java survey</title>
		<link>https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mathworks-solicited-java-survey</link>
					<comments>https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 22 Mar 2017 22:05:34 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[uifigure]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6866</guid>

					<description><![CDATA[<p>MathWorks is soliciting user feedbacks about the use of Java components in Matlab programs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey">MathWorks-solicited Java survey</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/mathworks-blogs-facelift" rel="bookmark" title="MathWorks blogs facelift">MathWorks blogs facelift </a> <small>MathWorks has just released a new look-&-feel for their blogs section. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-a-java-focus-problem" rel="bookmark" title="Fixing a Java focus problem">Fixing a Java focus problem </a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Over the years I&#8217;ve reported numerous uses for integrating Java components and functionality in Matlab. As I&#8217;ve also <a href="/articles/adding-a-search-box-to-figure-toolbar#uifigure" rel="nofollow" target="_blank">recently reported</a>, MathWorks is apparently making a gradual shift away from standalone Java-based figures, toward browser-based web-enabled figures. <a href="/articles/password-and-spinner-controls-in-matlab-gui#warning" target="_blank">As I surmised</a> a few months ago, MathWorks has created dedicated surveys to solicit user feedbacks on the most important (and undocumented) non-compatible aspects of this paradigm change: one regarding users&#8217; use of the <a href="/articles/javacomponent" rel="nofollow" target="_blank"><i><b>javacomponent</b></i> function</a>, the other regarding the use of the figure&#8217;s <a href="/articles/tag/javaframe" target="_blank"><b>JavaFrame</b> property</a>:</p>
<ul>
<li>Survey regarding usage of the <i><b>javacomponent</b></i> function: <a href="http://www.mathworks.com/javacomponent" rel="nofollow" target="_blank">http://www.mathworks.com/javacomponent</a></li>
<li>Survey regarding usage of the <b>JavaFrame</b> property: <a href="http://www.mathworks.com/javaframe" rel="nofollow" target="_blank">http://www.mathworks.com/javaframe</a></li>
</ul>
<p>In MathWorks&#8217; words:</p>
<blockquote><p>
In order to extend your ability to build MATLAB apps, we understand you sometimes need to make use of undocumented Java UI technologies, such as the JavaFrame property. In response to your needs, we are working to develop documented alternatives that address gaps in our app building offerings.<br />
To help inform our work and plans, we would like to understand how you are using the JavaFrame property. Based on your understanding of how it is being used within your app, please take a moment to fill out the following survey. The survey will take approximately 1-2 minutes to finish.
</p></blockquote>
<p>I urge anyone who uses one or both of these features to let MathWorks know how you&#8217;re using them, so that they could incorporate that functionality into the core (documented) Matlab. The surveys are really short and to the point. If you wish to send additional information, please email George.Caia at mathworks.com.<br />
The more feedback responses that MathWorks will get, the better it will be able to prioritize its R&#038;D efforts for the benefit of all users, and the more likely are certain features to get a documented solution at some future release. If you don&#8217;t take the time now to tell MathWorks how you use these features in your code, don&#8217;t complain if and when they break in the future&#8230;</p>
<h3 id="uses">My personal uses of these features</h3>
<ul>
<li><b>Functionality:</b>
<ul>
<li>Figure: maximize/minimize/restore, enable/disable, always-on-top, toolbar controls, menu customizations (icons, tooltips, font, shortcuts, colors)</li>
<li>Table: sorting, filtering, grouping, column auto-sizing, cell-specific behavior (tooltip, context menu, context-sensitive editor, merging cells)</li>
<li>Tree control</li>
<li>Listbox: cell-specific behavior (tooltip, context menu)</li>
<li>Tri-state checkbox</li>
<li>uicontrols in general: various event callbacks (e.g. mouse hover/unhover, focus gained/lost)</li>
<li>Ability to add Java controls e.g. color/font/date/file selector panel or dropdown, spinner, slider, search box, password field</li>
<li>Ability to add 3rd-party components e.g. JFreeCharts, JIDE controls/panels</li>
</ul>
<p></li>
<li><b>Appearance:</b>
<ul>
<li>Figure: undecorated (frameless), other figure frame aspects</li>
<li>Table: column/cell-specific rendering (alignment, icons, font, fg/bg color, string formatting)</li>
<li>Listbox: auto-hide vertical scrollbar as needed, cell-specific renderer (icon, font, alignment, fg/bg color)</li>
<li>Button/checkbox/radio: icons, text alignment, border customization, Look &#038; Feel</li>
<li>Right-aligned checkbox (button to the right of label)</li>
<li>Panel: border customization (rounded/matte/&#8230;)</li>
</ul>
</li>
</ul>
<p>You can find descriptions/explanations of many of these in posts I made on this website over the years.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey">MathWorks-solicited Java survey</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/mathworks-blogs-facelift" rel="bookmark" title="MathWorks blogs facelift">MathWorks blogs facelift </a> <small>MathWorks has just released a new look-&-feel for their blogs section. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-a-java-focus-problem" rel="bookmark" title="Fixing a Java focus problem">Fixing a Java focus problem </a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/mathworks-solicited-java-survey/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing uifigures part 1</title>
		<link>https://undocumentedmatlab.com/articles/customizing-uifigures-part-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-uifigures-part-1</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-uifigures-part-1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 21 Jul 2016 10:32:51 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[uifigure]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6554</guid>

					<description><![CDATA[<p>Matlab's new web-based  uifigures can be customized in a variety of undocumented ways. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-1">Customizing uifigures part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-3" rel="bookmark" title="Customizing uifigures part 3">Customizing uifigures part 3 </a> <small>As I have repeatedly posted in recent years, Matlab is advancing towards web-based GUI. The basic underlying technology is more-or-less stable: an HTML/Javascript webpage that is created-on-the-fly and rendered in a stripped-down browser window (based on Chromium-based jxBrowser in recent...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-2" rel="bookmark" title="Customizing uifigures part 2">Customizing uifigures part 2 </a> <small>Matlab's new web-based uifigures can be customized using custom CSS and Javascript code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-web-gui-uipanel" rel="bookmark" title="Customizing web-GUI uipanel">Customizing web-GUI uipanel </a> <small>We can customize Matlab's new web-based GUI panels in many interesting ways. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-print-setup" rel="bookmark" title="Customizing print setup">Customizing print setup </a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last month, I posted an article that summarized a variety of undocumented <a href="/articles/figure-window-customizations" target="_blank">customizations to Matlab figure windows</a>. As I noted in that post, Matlab figures have used Java <code>JFrame</code>s as their underlying technology since R14 (over a decade ago), but this is expected to change a few years from now with the advent of web-based <i><b>uifigure</b></i>s. <i><b>uifigure</b></i>s first became available in late 2014 with the new <a href="/articles/sliders-in-matlab-gui#AppDesigner" target="_blank">App Designer preview</a> (the much-awaited GUIDE replacement), and were <a href="http://www.mathworks.com/products/matlab/app-designer/" rel="nofollow" target="_blank">officially released in R2016a</a>. AppDesigner is actively being developed and we should expect to see exciting new features in upcoming Matlab releases.<br />
<center><figure style="width: 598px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab's new AppDesigner (a somewhat outdated screenshot)" src="https://undocumentedmatlab.com/images/slider_AppDesigner.png" title="Matlab's new AppDesigner (a somewhat outdated screenshot)" width="598" height="376" /><figcaption class="wp-caption-text">Matlab's new AppDesigner (a somewhat outdated screenshot)</figcaption></figure></center><br />
However, while AppDesigner has become officially supported, the underlying technology used for the new <i><b>uifigure</b></i>s remained undocumented. <span id="more-6554"></span>This is not surprising: MathWorks did a good job of retaining backward compatibility with the existing <i><b>figure</b></i> handle, and so a new <i><b>uifigure</b></i> returns a handle that programmatically appears similar to <i><b>figure</b></i> handles, reducing the migration cost when MathWorks decides (<a href="/articles/adding-a-search-box-to-figure-toolbar#uifigure" target="_blank">presumably around 2018-2020</a>) that web-based (rather than Java-based) figures should become the default <i><b>figure</b></i> type. By keeping the underlying figure technology undocumented and retaining the documented top-level behavior (properties and methods of the figure handle), Matlab users who only use the documented interface should expect a relatively smooth transition at that time.<br />
So does this mean that users who start using AppDesigner today (and especially in a few years when web figures become the default) can no longer enjoy the benefits of figure-based customization offered to the existing Java-based figure users (which I listed in last month&#8217;s post)? Absolutely not! All we need is to get a hook into the <i><b>uifigure</b></i>&#8216;s underlying object and then we can start having fun.</p>
<h3 id="Controller">The <i>uifigure</i> Controller</h3>
<p>One way to do this is to use the <i><b>uifigure</b></i> handle&#8217;s hidden (private) <b>Controller</b> property (a <code>matlab.ui.internal.controller.FigureController</code> MCOS object whose source-code appears in <i>%matlabroot%/toolbox/matlab/uitools/uicomponents/components/+matlab/+ui/+internal/+controller/</i>).<br />
<b>Controller</b> is not only a hidden but also a private property of the figure handle, so we cannot simply use the <i><b>get</b></i> function to get its value. This doesn&#8217;t stop us of course: We can get the controller object using either my <a href="/articles/getundoc-get-undocumented-object-properties" target="_blank"><i><b>getundoc</b></i> utility</a> or the builtin <i><b>struct</b></i> function (which <a href="/articles/accessing-private-object-properties" target="_blank">returns private/protected properties</a> as an undocumented feature):</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; hFig = uifigure<span style="color: #080;">(</span><span style="color:#A020F0;">'Name'</span>,<span style="color:#A020F0;">'Yair'</span>, <span style="color: #F0F;">...</span><span style="color: #080;">)</span>;
&nbsp;
&gt;&gt; figProps = <span style="color: #0000FF;">struct</span><span style="color: #080;">(</span>hFig<span style="color: #080;">)</span>;  <span style="color: #228B22;">% or getundoc(hFig)</span>
<span style="color: #F5B666;">Warning: Calling STRUCT on an object prevents the object from hiding its implementation details and should thus be
avoided. Use DISP or DISPLAY to see the visible public details of an object. See 'help struct' for more information.
(Type "<u>warning off MATLAB:structOnObject</u>" to suppress this warning.)</span>
&nbsp;
<span style="color: #F5B666;">Warning: figure JavaFrame property will be obsoleted in a future release. For more information see
<u>the JavaFrame resource on the MathWorks web site</u>.
(Type "<u>warning off MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame</u>" to suppress this warning.)</span>
&nbsp;
figProps =
                      JavaFrame: <span style="color: #080;">[</span><span style="color: #080;">]</span>
                    JavaFrame_I: <span style="color: #080;">[</span><span style="color: #080;">]</span>
                       Position: <span style="color: #080;">[</span><span style="color: #33f;">87</span> <span style="color: #33f;">40</span> <span style="color: #33f;">584</span> <span style="color: #33f;">465</span><span style="color: #080;">]</span>
                   PositionMode: <span style="color:#A020F0;">'auto'</span>
                            <span style="color: #F0F;">...</span>
                     <span style="">Controller</span>: <span style="color: #080;">[</span>1x1 matlab.<span style="">ui</span>.<span style="">internal</span>.<span style="">controller</span>.<span style="">FigureController</span><span style="color: #080;">]</span>
                 ControllerMode: <span style="color:#A020F0;">'auto'</span>
                            <span style="color: #F0F;">...</span>
&nbsp;
&gt;&gt; figProps.<span style="">Controller</span>
ans =
  FigureController with <span style="color: #0000FF;">properties</span>:
&nbsp;
       Canvas: <span style="color: #080;">[</span><span style="color: #080;">]</span>
    ProxyView: <span style="color: #080;">[</span>1x1 <span style="color: #0000FF;">struct</span><span style="color: #080;">]</span>
&nbsp;
&gt;&gt; figProps.<span style="">Controller</span>.<span style="">ProxyView</span>
ans =
            PeerNode: <span style="color: #080;">[</span>1x1 com.<span style="">mathworks</span>.<span style="">peermodel</span>.<span style="">impl</span>.<span style="">PeerNodeImpl</span><span style="color: #080;">]</span>
    PeerModelManager: <span style="color: #080;">[</span>1x1 com.<span style="">mathworks</span>.<span style="">peermodel</span>.<span style="">impl</span>.<span style="">PeerModelManagerImpl</span><span style="color: #080;">]</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">struct</span><span style="color: #080;">(</span>figProps.<span style="">Controller</span><span style="color: #080;">)</span>
<span style="color: #F5B666;">Warning: Calling STRUCT on an object prevents the object from hiding its implementation details and should thus be
avoided. Use DISP or DISPLAY to see the visible public details of an object. See 'help struct' for more information.
(Type "<u>warning off MATLAB:structOnObject</u>" to suppress this warning.)</span>
&nbsp;
ans =
               PositionListener: <span style="color: #080;">[</span>1x1 event.<span style="">listener</span><span style="color: #080;">]</span>
    ContainerPositionCorrection: <span style="color: #080;">[</span><span style="color: #33f;">1</span> <span style="color: #33f;">1</span> <span style="color: #33f;">0</span> <span style="color: #33f;">0</span><span style="color: #080;">]</span>
                      Container: <span style="color: #080;">[</span>1x1 matlab.<span style="">ui</span>.<span style="">internal</span>.<span style="">controller</span>.<span style="">FigureContainer</span><span style="color: #080;">]</span>
                         Canvas: <span style="color: #080;">[</span><span style="color: #080;">]</span>
                  IsClientReady: <span style="color: #33f;">1</span>
              PeerEventListener: <span style="color: #080;">[</span>1x1 <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">]</span>
                      ProxyView: <span style="color: #080;">[</span>1x1 <span style="color: #0000FF;">struct</span><span style="color: #080;">]</span>
                          Model: <span style="color: #080;">[</span>1x1 <span style="color: #0000FF;">Figure</span><span style="color: #080;">]</span>
               ParentController: <span style="color: #080;">[</span>0x0 handle<span style="color: #080;">]</span>
      PropertyManagementService: <span style="color: #080;">[</span>1x1 matlab.<span style="">ui</span>.<span style="">internal</span>.<span style="">componentframework</span>.<span style="">services</span>.<span style="">core</span>.<span style="">propertymanagement</span>.<span style="">PropertyManagementService</span><span style="color: #080;">]</span>
          IdentificationService: <span style="color: #080;">[</span>1x1 matlab.<span style="">ui</span>.<span style="">internal</span>.<span style="">componentframework</span>.<span style="">services</span>.<span style="">core</span>.<span style="">identification</span>.<span style="">WebIdentificationService</span><span style="color: #080;">]</span>
           EventHandlingService: <span style="color: #080;">[</span>1x1 matlab.<span style="">ui</span>.<span style="">internal</span>.<span style="">componentframework</span>.<span style="">services</span>.<span style="">core</span>.<span style="">eventhandling</span>.<span style="">WebEventHandlingService</span><span style="color: #080;">]</span></pre>
</div>
</div>
<p>I will discuss all the goodies here in a future post (if you are curious then feel free to start drilling in there yourself, I promise it won&#8217;t bite you&#8230;). However, today I wish to concentrate on more immediate benefits from a different venue:</p>
<h3 id="webwindow">The <i>uifigure</i> webwindow</h3>
<p><i><b>uifigure</b></i>s are basically webpages rather than desktop windows (JFrames). They use an entirely different UI mechanism, based on HTML webpages served from a localhost webserver that runs CEF (<a href="https://en.wikipedia.org/wiki/Chromium_Embedded_Framework" rel="nofollow" target="_blank">Chromium Embedded Framework</a> version 3.2272 on <a href="https://www.chromium.org/developers/calendar" rel="nofollow" target="_blank">Chromium 41</a> in R2016a). This runs the so-called CEF client (apparently an adaptation of the CefClient sample application that comes with CEF; the relevant Matlab source-code is in <i>%matlabroot%/toolbox/matlab/cefclient/</i>). It uses the <a href="https://dojotoolkit.org" rel="nofollow" target="_blank">DOJO Javascript toolkit</a> for UI controls visualization and interaction, rather than Java Swing as in the existing JFrame figures. I still don&#8217;t know if there is a way to combine the seemingly disparate sets of GUIs (namely adding Java-based controls to web-based figures or vice-versa).<br />
Anyway, the important thing to note for my purposes today is that when a new <i><b>uifigure</b></i> is created, the above-mentioned Controller object is created, which in turn creates a new <code>matlab.internal.webwindow</code>. The webwindow class (<i>%matlabroot%/toolbox/matlab/cefclient/+matlab/+internal/webwindow.m</i>) is well-documented and easy to follow (although the non camel-cased class name escaped someone&#8217;s attention), and allows access to several important figure-level customizations.<br />
The figure&#8217;s <code>webwindow</code> reference can be accessed via the <b>Controller</b>&#8216;s <b>Container</b>&#8216;s <b>CEF</b> property:</p>
<pre lang="matlab">
>> hFig = uifigure('Name','Yair', ...);
>> warning off MATLAB:structOnObject      % suppress warning (yes, we know it's naughty...)
>> figProps = struct(hFig);
>> controller = figProps.Controller;      % Controller is a private hidden property of Figure
>> controllerProps = struct(controller);
>> container = controllerProps.Container  % Container is a private hidden property of FigureController
container =
  FigureContainer with properties:
    FigurePeerNode: [1x1 com.mathworks.peermodel.impl.PeerNodeImpl]
         Resizable: 1
          Position: [86 39 584 465]
               Tag: ''
             Title: 'Yair'
              Icon: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\uitools\uicomponents\resources\images…'
           Visible: 1
               URL: 'http://localhost:31417/toolbox/matlab/uitools/uifigureappjs/componentContainer.html…'
              HTML: 'toolbox/matlab/uitools/uifigureappjs/componentContainer.html'
     ConnectorPort: 31417
         DebugPort: 0
     IsWindowValid: 1
>> win = container.CEF   % CEF is a regular (public) hidden property of FigureContainer
win =
  webwindow with properties:
                             URL: 'http://localhost:31417/toolbox/matlab/uitools/uifigureappjs/component…'
                           Title: 'Yair'
                            Icon: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\uitools\uicomponents\re…'
                        Position: [86 39 584 465]
     CustomWindowClosingCallback: @(o,e)this.Model.hgclose()
    CustomWindowResizingCallback: @(event,data)resizeRequest(this,event,data)
                  WindowResizing: []
                   WindowResized: []
                     FocusGained: []
                       FocusLost: []
                DownloadCallback: []
        PageLoadFinishedCallback: []
           MATLABClosingCallback: []
      MATLABWindowExitedCallback: []
             PopUpWindowCallback: []
             RemoteDebuggingPort: 0
                      CEFVersion: '3.2272.2072'
                 ChromiumVersion: '41.0.2272.76'
                   isWindowValid: 1
               isDownloadingFile: 0
                         isModal: 0
                  isWindowActive: 1
                   isAlwaysOnTop: 0
                     isAllActive: 1
                     isResizable: 1
                         MaxSize: []
                         MinSize: []
>> win.URL
ans =
http://localhost:31417/toolbox/matlab/uitools/uifigureappjs/componentContainer.html?channel=/uicontainer/393ed66a-5e34-41f3-8ac0-0b0f3b0738cd&snc=5C2353
</pre>
<p>An alternative way to get the <code>webwindow</code> is via the list of all <code>webwindow</code>s stored by a central <code>webwindowmanager</code>:</p>
<pre lang="matlab">
webWindows = matlab.internal.webwindowmanager.instance.findAllWebwindows();  % manager method returning an array of all open webwindows
webWindows = matlab.internal.webwindowmanager.instance.windowList;           % equivalent alternative via manager's windowList property
</pre>
<p>Note that the controller, container and webwindow class objects, like most Matlab MCOS objects, have internal (hidden) properties/methods that you can explore. For example:</p>
<pre lang="matlab">
>> getundoc(win)
ans =
                   Channel: [1x1 asyncio.Channel]
       CustomEventListener: [1x1 event.listener]
           InitialPosition: [100 100 600 400]
    JavaScriptReturnStatus: []
     JavaScriptReturnValue: []
     NewWindowBeingCreated: 0
          NewWindowCreated: 1
           UpdatedPosition: [86 39 584 465]
              WindowHandle: 2559756
                    newURL: 'http://localhost:31417/toolbox/matlab/uitools/uifigureappjs/componentContai…'
</pre>
<h3 id="customizations">Using webwindow for figure-level customizations</h3>
<p>We can use the methods of this <code>webwindow</code> object as follows:</p>
<pre lang="matlab">
win.setAlwaysOnTop(true);   % always on top of other figure windows (a.k.a. AOT)
win.hide();
win.show();
win.bringToFront();
win.minimize();
win.maximize();
win.restore();
win.setMaxSize([400,600]);  % enables resizing up to this size but not larger (default=[])
win.setMinSize([200,300]);  % enables resizing down to this size but not smaller (default=[])
win.setResizable(false);
win.setWindowAsModal(true);
win.setActivateCurrentWindow(false);  % disable interaction with this entire window
win.setActivateAllWindows(false);     % disable interaction with *ALL* uifigure (but not Java-based) windows
result = win.executeJS(jsStr, timeout);  % run JavaScript
</pre>
<p>In addition to these methods, we can set callback functions to various callbacks exposed by the <code>webwindow</code> as regular properties (too bad that some of their names [like the class name itself] don&#8217;t follow Matlab&#8217;s standard naming convention, in this case by appending &#8220;Fcn&#8221; or &#8220;Callback&#8221;):</p>
<pre lang="matlab">
win.FocusGained = @someCallbackFunc;
win.FocusLost = @anotherCallbackFunc;
</pre>
<p>In summary, while the possible <a href="/articles/figure-window-customizations" target="_blank">customizations to Java-based figure windows</a> are more extensive, the <code>webwindow</code> methods appear to cover most of the important ones. Since these functionalities (maximize/minimize, AOT, disable etc.) are now common to both the Java and web-based figures, I really hope that MathWorks will create fully-documented <i><b>figure</b></i> properties/methods for them. Now that there is no longer any question whether these features will be supported by the future technology, and since there is no question as to their usefulness, there is really no reason not to officially support them in both figure types. If you feel the same as I do, please let MathWorks know about this &#8211; if enough people request this, MathWorks will be more likely to add these features to one of the upcoming Matlab releases.<br />
<b><u>Warning</u></b>: the internal implementation is subject to change across releases, so be careful to make your code cross-release compatible whenever you rely on one of Matlab&#8217;s internal objects.<br />
Note that I labeled this post as &#8220;part 1&#8221; &#8211; I expect to post additional articles on <i><b>uifigure</b></i> customizations in upcoming years. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-1">Customizing uifigures part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-3" rel="bookmark" title="Customizing uifigures part 3">Customizing uifigures part 3 </a> <small>As I have repeatedly posted in recent years, Matlab is advancing towards web-based GUI. The basic underlying technology is more-or-less stable: an HTML/Javascript webpage that is created-on-the-fly and rendered in a stripped-down browser window (based on Chromium-based jxBrowser in recent...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-2" rel="bookmark" title="Customizing uifigures part 2">Customizing uifigures part 2 </a> <small>Matlab's new web-based uifigures can be customized using custom CSS and Javascript code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-web-gui-uipanel" rel="bookmark" title="Customizing web-GUI uipanel">Customizing web-GUI uipanel </a> <small>We can customize Matlab's new web-based GUI panels in many interesting ways. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-print-setup" rel="bookmark" title="Customizing print setup">Customizing print setup </a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-uifigures-part-1/feed</wfw:commentRss>
			<slash:comments>24</slash:comments>
		
		
			</item>
		<item>
		<title>Figure window customizations</title>
		<link>https://undocumentedmatlab.com/articles/figure-window-customizations?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=figure-window-customizations</link>
					<comments>https://undocumentedmatlab.com/articles/figure-window-customizations#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 01 Jun 2016 08:00:11 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6439</guid>

					<description><![CDATA[<p>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/figure-window-customizations">Figure window customizations</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/minimize-maximize-figure-window" rel="bookmark" title="Minimize/maximize figure window">Minimize/maximize figure window </a> <small>Matlab figure windows can easily be maximized, minimized and restored using a bit of undocumented magic powder...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A friend recently asked me, in light of <a href="/articles/adding-a-search-box-to-figure-toolbar#uifigure" target="_blank">my guesstimate</a> that Java-based Matlab figures will be replaced by web-based figures sometime around 2018-2020, whether there are any &#8220;killer features&#8221; that make it worthwhile to use undocumented Java-based tricks today, despite the fact that they will probably break in 2-5 years. In my opinion, there are many such features; today I will focus on just a subset of them &#8211; those features that relate to the entire figure window.<br />
Over the years I wrote many articles here about <a href="/articles/tag/javaframe" target="_blank">figure-level customizations</a>, as well as an entire chapter in my <a href="/books/matlab-java" target="_blank">Matlab-Java programming book</a>. So today&#8217;s post will be a high-level overview, and users who are interested in any specific topic can visit the referenced links for the implementation details.<br />
<center><img decoding="async" alt="An undecorated Matlab figure window - one of many possible figure-level customizations" src="https://undocumentedmatlab.com/images/undecorated_figure.gif" title="An undecorated Matlab figure window - one of many possible figure-level customizations" width="80%" style="max-width: 616px;" /><br />An undecorated Matlab figure window &#8211; one of many possible figure-level customizations</center><br />
<span id="more-6439"></span></p>
<h3 id="JavaFrame">JavaFrame</h3>
<p><a href="/articles/minimize-maximize-figure-window/#JavaFrame" target="_blank"><b>JavaFrame</b></a> is an undocumented hidden property of the figure handle that provides access to the underlying Java window (<code>JFrame</code>) peer object&#8217;s reference. Since R2008a, a warning is issued whenever we retrieve this property:</p>
<div class="wp_syntax">
<div class="code">
<pre style="font-family: monospace;"><span style="color: #000000;">>> jFrame = </span><span style="color: #0000ff;">get</span>(<span style="color: #0000ff;">gcf</span>,<span style="color: #800080;">'JavaFrame'</span>);
<span style="color: #ff0000;">Warning: figure JavaFrame property will be obsoleted in a future release.</span>
<span style="color: #000000;">For more information see the JavaFrame resource on the MathWorks web site.
(Type "warning off MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame" to suppress this warning.)
</pre>
</div>
</div>
<p>Until HG2 (R2014b+) we could suppress the warning by simply wrapping the figure handle within a <i><b>handle()</b></i> call, as <a href="/articles/minimize-maximize-figure-window/#JavaFrame" target="_blank">explained here</a>. Since R2014b we need to use the <i><b>warning</b></i> function to do this:</p>
<pre lang="matlab">warning('off', 'MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');</pre>
<p>We can do several things directly with the <b>JavaFrame</b>&#8216;s properties and methods, including:</p>
<ul>
<li>Maximize/minimize/restore the window, via the properties <b>Maximized</b>/<b>Minimized</b> (which accept and return a boolean (logical) value), or the corresponding methods <i>jFrame.isMaximized(), isMinimized(), setMaximized(flag), setMinimized(flag)</i>. <a href="/articles/minimize-maximize-figure-window" target="_blank">details</a></li>
<li>Modify the container to which the figure will be docked. By default this is the &#8220;Figures&#8221; container, but this can be changed to any user-specified container, or even to the &#8220;Editor&#8221;, using the <b>GroupName</b> property or its associated methods. See the related <a href="http://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup" rel="nofollow" target="_blank"><i><b>setFigDockGroup</b></i> utility</a> that I posted on the Matlab File exchange.</li>
<li>Remove the top separator line between the toolbar and the content-pane, to blend them together, via the <i>jFrame.showTopSeparator(flag)</i> method.</li>
<li>Retrieve a direct Java reference to the Matlab Desktop and the figure&#8217;s internal containers via the <b>Desktop</b> and <b>FigurePanelContainer</b> properties, respectively (we can also get those references by other means).</li>
<li>Retrieve a direct Java reference to the containing <code>JFrame</code> (Java window), as discussed below</li>
<li>A few other features that I will not discuss here</li>
</ul>
<p>MathWorks have set up a dedicated webpage where you can specify how you are using <b>JavaFrame</b> and why it is important for you: <a href="http://www.mathworks.com/javaframe" rel="nofollow" target="_blank">http://www.mathworks.com/javaframe</a>. I encourage you to use this webpage to tell MathWorks which features are important for you. This will help them to decide which functionality should be added to the new web-based figures.</p>
<h3 id="JFrame">JFrame window</h3>
<p>The <b>JavaFrame</b> handle enables direct retrieval of the containing Java <a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html" rel="nofollow" target="_blank"><code>JFrame</code></a> (window) reference, using several alternatives. Here are two of these alternatives (there are others):</p>
<pre lang="matlab">
% Alternative #1
>> jWindow = jFrame.getFigurePanelContainer.getTopLevelAncestor
jWindow =
com.mathworks.hg.peer.FigureFrameProxy$FigureFrame[fClientProxyFrame,72,62,576x507,...]
% Alternative #2
try
    jClient = jFrame.fFigureClient;  % This works up to R2011a
catch
    try
        jClient = jFrame.fHG1Client;  % This works from R2008b-R2014a
    catch
        jClient = jFrame.fHG2Client;  % This works from R2014b and up
    end
end
jWindow = jClient.getWindow;
</pre>
<p><figure style="width: 400px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Customized menu items" src="https://undocumentedmatlab.com/images/uimenu1.png" title="Customized menu items" width="202" height="200" /> <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/uimenu7a.png" alt="Customized menu items" title="Customized menu items" width="160" height="180" /><br />
<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/statusbar_animated.gif" alt="Integrated figure status bar" title="Integrated figure status bar" width="400" height="253" /><figcaption class="wp-caption-text">Customized menu items (top) and figure status bar (bottom)</figcaption></figure>With the retrieved <code>jWindow</code> reference, we can do several additional interesting things:</p>
<ul>
<li>Enable/disable the entire figure in a single go (<a href="/articles/disable-entire-figure-window" target="_blank">details</a>)</li>
<li>Remove/restore the window frame (borders and title bar), otherwise known as an &#8220;undecorated window&#8221; (<a href="/articles/frameless-undecorated-figure-windows" target="_blank">details</a>)</li>
<li>Set the figure window to be &#8220;Always-On-Top&#8221;, i.e. not occluded by any other window, via the <b>AlwaysOnTop</b> property, or the corresponding <i>jWindow.isAlwaysOnTop(), setAlwaysOnTop(flag)</i> methods.</li>
<li>Make the figure window fully or partially transparent (<a href="/articles/transparent-matlab-figure-window" target="_blank">details</a>). Note: this fails on R2013b/Java7 and higher due to a change in the way that transparency works in Java 7 compared to earlier releases; in other words blame Oracle&#8217;s Java, not MathWorks&#8217; Matlab&#8230;.</li>
<li>Blur/restore the figure window (<a href="/articles/blurred-matlab-figure-window" target="_blank">details</a>). This too works only up to R2013a.</li>
<li>Detect and handle window-level focus gain/loss events (<a href="/articles/detecting-window-focus-events" rel="nofollow" target="_blank">details</a>), as well as window-level mouse events (enter/exit/hover etc. &#8211; <a href="/articles/matlab-callbacks-for-java-events-in-r2014a" target="_blank">details</a>).</li>
<li>Customize the figure&#8217;s menu bar &#8211; dynamic behavior, tooltips, highlights, keyboard shortcuts/accelerators, font colors/styles, callbacks, icons etc. (<a href="/articles/customizing-menu-items-part-2" target="_blank">details1</a>, <a href="/articles/customizing-menu-items-part-3" target="_blank">details2</a>)</li>
<li>Control figure docking in compiled (deployed) applications (<a href="/articles/docking-figures-in-compiled-applications" target="_blank">details1</a>, <a href="/articles/disabling-menu-entries-in-deployed-docked-figures" target="_blank">details2</a>)</li>
<li>Display an integral figure status-bar with text and GUI controls (<a href="/articles/setting-status-bar-text" target="_blank">details1</a>, <a href="/articles/setting-status-bar-components" target="_blank">details2</a>).</li>
<li>A few other features that I will not discuss here</li>
</ul>
<p>As you can see, there are numerous very interesting customizations that can be done to Matlab figures which rely on the undocumented implementation. Here are a couple of usage examples that you can easily adapt (follow the links above for additional details and usage examples):</p>
<pre lang="matlab">
jWindow.setEnabled(false);     % disable entire figure [true/false]
jWindow.setMinimized(true);    % minimize window [true/false]
jWindow.setMaximized(true);    % maximize window [true/false]
jWindow.setAlwaysOnTop(true);  % set to be always on top [true/false]
% Set a Matlab callback function to a window focus-gain event
hjWindow = handle(jWindow, 'CallbackProperties');
hjWindow.FocusGainedCallback = @myCallbackFunc;
</pre>
<p>In addition to the Java-based features above, some functionalities can also be achieved via direct OS manipulations, for example using Jan Simon&#8217;s great <a href="http://www.mathworks.com/matlabcentral/fileexchange/31437-windowapi" rel="nofollow" target="_blank">WindowAPI utility</a> (Windows-only), although I typically prefer using the Java approach since it is cross-platform compatible.<br />
Using all these features is super-easy, so there is not really a question of code complexity or technical risk &#8211; the main question is whether to accept the risk that the associated code will stop working when Matlab figures will eventually become web-based.</p>
<h3 id="risk">So is it worth the risk?</h3>
<p>This is an excellent question. I contend that the answer depends on the specific use-case. In one project you may decide that it is indeed worth-while to use these undocumented features today, whereas in another GUI you may decide that it is not.<br />
It might make sense to use the features above in any of the following circumstances:</p>
<ul>
<li>If you need any of the features in your Matlab GUI today. In this case, you really have no alternative other than to use these features, since there is no documented way to achieve the required functionality.</li>
<li>If you do not plan to upgrade your Matlab release soon, or at least after the Java-based figures are discontinued in a few years. The commercial Matlab license is perpetual, enabling users to enjoy these features for as long as they continue using this Matlab release.</li>
<li>If you are compiling your Matlab program using the Matlab Compiler or Coder toolboxes. In such cases, the executable will remain static, until such time (if ever) that you decide to recompile it using a newer Matlab release. Users of the compiled code could continue to use the compiled undocumented features well into the future, for as long as their computers keep running. In such cases, we are not concerned with release compatibility issues.</li>
<li>If you accept the risk that some recoding may be necessary in the future, or that some functionality will degrade, for the added benefit that they provide your GUIs today.</li>
<li>If you are willing to code without MathWorks&#8217; official support and endorsement, and accept the fact that they will not fix any internal bugs that you may discover which is related to these features.</li>
<li>If you wish to present a professional-grade GUI today, and worry about potential incompatibilities only if and when they eventually arrive, sometime in the future.</li>
</ul>
<p>Here&#8217;s another twist to consider: do <b>not</b> take it for granted that when web-based uifigures replace Java-based figures all the documented functionality will work as-is on the new uifigures just as they have on the old figures. In fact, I personally believe that we will need to extensively modify our GUI code to make it compatible with the new uifigures. In other words, avoiding the undocumented hacks above will probably not save us from the need to recode (or at least adapt) our GUI, it will just reduce the necessary work somewhat. We encountered a similar situation with the graphics hacks that I exposed over the years: many people avoided them in the fear that they might someday break; then when R2014b came and HG2 graphics replaced HG1, it turned out that many of these supposedly risky hacks continued working in HG2 (examples: <a href="/articles/axes-looseinset-property" target="_blank">LooseInset</a>, <a href="/articles/plot-liminclude-properties" target="_blank">YLimInclude</a>) whereas quite a bit of standard fully-documented Matlab functionality was broken and required some recoding. I believe that the lessons from the HG2 migration were well studied and assimilated by MathWorks, but realistically speaking we should not expect a 100% full-proof transition to uifigures.<br />
Still, accepting the risk does not mean that we should bury our head in the sand. Whenever using any undocumented feature in your code, I strongly suggest to use defensive coding practices, such as wrapping your code within <i><b>try-catch</b></i> blocks. This way, even if the feature is removed in R2020a (or whenever), the program will still run, albeit with somewhat diminished functionality, or in other words, <i>graceful degradation</i>. For example:</p>
<pre lang="matlab">
try
    jFrame = get(hFig, 'JavaFrame');
    jFrame.setMaximized(true);
catch
    oldUnits = get(hFig, 'Units');
    set(hFig, 'Units','norm', 'Pos',[0,0,1,1]);
    set(hFig, 'Units',oldUnits);
end
</pre>
<p>Once again, I urge you to visit <a href="http://www.mathworks.com/javaframe" rel="nofollow" target="_blank">http://www.mathworks.com/javaframe</a> and tell MathWorks which of the above features are important for you. The more users tell MathWorks that they depend on a specific feature, the more would MathWorks be likely to invest R&#038;D efforts in enabling it in the future web-based figures.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/figure-window-customizations">Figure window customizations</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/minimize-maximize-figure-window" rel="bookmark" title="Minimize/maximize figure window">Minimize/maximize figure window </a> <small>Matlab figure windows can easily be maximized, minimized and restored using a bit of undocumented magic powder...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/figure-window-customizations/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-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-contour-plots-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 Mar 2016 18:00:49 +0000</pubDate>
				<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6304</guid>

					<description><![CDATA[<p>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2">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-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" 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-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-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few months ago <a href="/articles/customizing-contour-plots" target="_blank">I discussed</a> various undocumented manners by which we can customize Matlab contour plots. A short while ago I receive an email from a blog reader (thanks Frank!) alerting me to another interesting way by which we can customize such plots, using the contour handle&#8217;s hidden <b>ContourZLevel</b> property. In today&#8217;s post I will explain how we can use this property and expand the discussion with some visualization interactivity.</p>
<h3 id="ContourZLevel">The ContourZLevel property</h3>
<p>The contour handle&#8217;s <b>ContourZLevel</b> property is a hidden property. This means that, just like all other hidden properties, it is accessible if we just happen to know its name (which is easy using my <a href="/articles/getundoc-get-undocumented-object-properties" rel="nofollow" target="_blank"><i><b>getundoc</b></i> utility</a>). This property sets the Z level at which the contour lines are drawn.<br />
For example, by default the <i><b>meshc</b></i> function sets <b>ContourZLevel</b>&#8216;s value to the bottom of the 3D display (in other words, to the axes&#8217; <b>ZLim</b>(1) value). This is done within the <i>mesh.m</i> function:<br />
<center><figure style="width: 350px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Standard Matlab meshc output (contour at bottom)" src="https://undocumentedmatlab.com/images/meshc1.png" title="Standard Matlab meshc output (contour at bottom)" width="350" height="255" /><figcaption class="wp-caption-text">Standard Matlab meshc output (contour at bottom)</figcaption></figure></center><br />
We can, however, modify the contour&#8217;s level value to any other Z location:<br />
<span id="more-6304"></span></p>
<pre lang="matlab">
% create a mesh and contour plot
handles = meshc(peaks);
% handles is a 2-element array of handles: the surface plot and the contours
hContour = handles(2); % get the handle to the contour lines
hContour.ContourZLevel = 4.5; % set the contour's Z position (default: hAxes.ZLim(1)=-10)
% We can also customize other aspects of the contour lines, for example:
hContour.LineWidth = 2; % set the contour lines' width (default: 0.5)
</pre>
<p><center><figure style="width: 344px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized Matlab meshc output" src="https://undocumentedmatlab.com/images/meshc2.png" title="Customized Matlab meshc output" width="344" height="255" /><figcaption class="wp-caption-text">Customized Matlab meshc output</figcaption></figure></center></p>
<h3 id="interactivity">Adding some visualization interactivity</h3>
<p>Now let&#8217;s add some fun interactivity using a vertical slider to control the contour&#8217;s height (Z level). Matlab&#8217;s slider uicontrol is really just an ugly scrollbar, so we&#8217;ll use a Java <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/slider.html" rel="nofollow" target="_blank">JSlider</a> instead:</p>
<pre lang="matlab">
% Add a controlling slider to the figure
jSlider = javaObjectEDT(javax.swing.JSlider);
jSlider.setOrientation(jSlider.VERTICAL);
jSlider.setPaintTicks(true);
jSlider.setMajorTickSpacing(20);
jSlider.setMinorTickSpacing(5);
jSlider.setBackground(java.awt.Color.white);
[hjSlider, hContainer] = javacomponent(jSlider, [10,10,30,120], gcf);
% Set the slider's action callback
hAxes = hContour.Parent;  % handle to containing axes
zmin = hAxes.ZLim(1);
zmax = hAxes.ZLim(2);
zrange = zmax - zmin;
cbFunc = @(hSlider,evtData) set(hContour,'ContourZLevel',hSlider.getValue/100*zrange+zmin);
hjSlider.StateChangedCallback = cbFunc;  % set the callback for slider action events
cbFunc(hjSlider,[]);  % evaluate the callback to synchronize the initial display
</pre>
<p><center><figure style="width: 392px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Interactive contour height" src="https://undocumentedmatlab.com/images/meshc_animated.gif" title="Interactive contour height" width="392" height="256" /><figcaption class="wp-caption-text">Interactive contour height</figcaption></figure></center></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2">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-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" 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-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-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing contour plots</title>
		<link>https://undocumentedmatlab.com/articles/customizing-contour-plots?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-contour-plots</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-contour-plots#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 Nov 2015 18:00:55 +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[BeanAdapter]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6075</guid>

					<description><![CDATA[<p>Contour labels, lines and fill patches can easily be customized in Matlab HG2. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots">Customizing contour 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-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-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/hidden-hg2-plot-functionality" rel="bookmark" title="Accessing hidden HG2 plot functionality">Accessing hidden HG2 plot functionality </a> <small>In HG2, some of the plot functionality is hidden in undocumented properties. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>One of my clients asked me last week whether it is possible to access and customize individual contour lines and labels in HG2 (Matlab&#8217;s new graphics system, R2014+). Today&#8217;s post will discuss how this could indeed be done.<br />
<figure style="width: 404px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Matlab contour plot" src="https://undocumentedmatlab.com/images/contour.gif" title="Matlab contour plot" width="404" height="307" /><figcaption class="wp-caption-text">Matlab contour plot</figcaption></figure> In HG1 (R2014a and earlier), contour handles were simple <code>hggroup</code> objects that incorporated <code>text</code> and <code>patch</code> child handles. The contour labels, lines and fill patches could easily be accessed via these child handles (contour lines and fills use the same patch object: the lines are simply the patch edges; fills are their faces). The lines could then be customized, the label strings changed, and the patch faces (fills) recolored:</p>
<pre lang='matlab'>
[X,Y,Z] = peaks;
[C,hContour] = contour(X,Y,Z,20, 'ShowText','on');
hChildren = get(hContour, 'Children');
set(hChildren(1), 'String','Yair', 'Color','b');  % 1st text (contour label)
set(hChildren(end), 'EdgeColor',[0,1,1]);         % last patch (contour line)
</pre>
<p>The problem is that in HG2 (R2014b onward), <i><b>contour</b></i> (and its sibling functions, <i><b>contourf</b></i> etc.) return a graphic object that has no accessible children. In other words, <code>hContour.Children</code> returns an empty array:</p>
<pre lang='matlab'>
>> hContour.Children
ans =
  0x0 empty GraphicsPlaceholder array.
>> allchild(hContour)
ans =
  0x0 empty GraphicsPlaceholder array.
>> isempty(hContour.Children)
ans =
     1
</pre>
<p>So how then can we access the internal contour patches and labels?<br />
<span id="more-6075"></span></p>
<h3 id="hg2">HG2&#8217;s contour object&#8217;s hidden properties</h3>
<p>Skipping several fruitless dead-ends, it turns out that in HG2 the text labels, lines and fills are stored in undocumented hidden properties called <b>TextPrims</b>, <b>EdgePrims</b> and (surprise, surprise) <b>FacePrims</b>, which hold corresponding arrays of <code>matlab.graphics.primitive.world.Text</code>, <code>matlab.graphics.primitive.world.LineStrip</code> and <code>matlab.graphics.primitive.world.TriangleStrip</code> object handles (the <i><b>drawnow</b></i> part is also apparently very important, otherwise you might get errors due to the Prim objects not being ready by the time the code is reached):</p>
<pre lang='matlab'>
>> drawnow;  % very important!
>> hContour.TextPrims  % row array of Text objects
ans =
  1x41 Text array:
  Columns 1 through 14
    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text
  Columns 15 through 28
    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text
  Columns 29 through 41
    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text
>> hContour.EdgePrims  % column array of LineStrip objects
ans =
  20x1 LineStrip array:
  ineStrip
  LineStrip
  LineStrip
  ...
>> hContour.FacePrims  % column array of TriangleStrip objects (empty if no fill)
ans =
  0x0 empty TriangleStrip array.
</pre>
<p>We can now access and customize the individual contour lines, labels and fills:</p>
<pre lang='matlab'>
hContour.TextPrims(4).String = 'Dani';
hContour.TextPrims(7).Visible = 'off';
hContour.TextPrims(9).VertexData = single([-1.3; 0.5; 0]);  % Label location in data units
hContour.EdgePrims(2).ColorData = uint8([0;255;255;255]);  % opaque cyan
hContour.EdgePrims(5).Visible = 'off';
</pre>
<p>Note that the <code>LineStrip</code> objects here are the same as those used for the axes Axles, <a target="_blank" href="/articles/customizing-axes-rulers#Axle">which I described</a> a few months ago. Any customization that we could do to the axle <code>LineStrip</code>s can also be applied to contour <code>LineStrip</code>s, and vice versa.<br />
For example, to achieve the appearance of a <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Topographic_map">topographic map</a>, we might want to modify some contour lines to use dotted <b>LineStyle</b> and other lines to appear bold by having larger <b>LineWidth</b>. Similarly, we may wish to hide some labels (by setting their <b>Visible</b> property to &#8216;off&#8217;) and make other labels bold (by setting their <b>Font.Weight</b> property to &#8216;bold&#8217;). There are really numerous customization possibilities here.<br />
Here is a listing of the standard (non-hidden) properties exposed by these objects:</p>
<pre lang='matlab'>
>> get(hContour.TextPrims(1))
        BackgroundColor: []
              ColorData: []
              EdgeColor: []
                   Font: [1x1 matlab.graphics.general.Font]
          FontSmoothing: 'on'
       HandleVisibility: 'on'
                HitTest: 'off'
    HorizontalAlignment: 'center'
            Interpreter: 'none'
                  Layer: 'middle'
              LineStyle: 'solid'
              LineWidth: 1
                 Margin: 1
                 Parent: [1x1 Contour]
          PickableParts: 'visible'
               Rotation: 7.24591082075548
                 String: '-5.1541'
          StringBinding: 'copy'
             VertexData: [3x1 single]
      VerticalAlignment: 'middle'
                Visible: 'on'
>> get(hContour.EdgePrims(1))
          AlignVertexCenters: 'off'
             AmbientStrength: 0.3
                ColorBinding: 'object'
                   ColorData: [4x1 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: [1x1 Contour]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: [1 18]
                     Texture: [0x0 GraphicsPlaceholder]
                  VertexData: [3x17 single]
               VertexIndices: []
                     Visible: 'on'
       WideLineRenderingHint: 'software'
>> get(hContour.FacePrims(1))
             AmbientStrength: 0.3
             BackFaceCulling: 'none'
                ColorBinding: 'object'
                   ColorData: [4x1 uint8]
                   ColorType: 'truecolor'
             DiffuseStrength: 0.6
            HandleVisibility: 'on'
                     HitTest: 'off'
                       Layer: 'middle'
               NormalBinding: 'none'
                  NormalData: []
                      Parent: [1x1 Contour]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: [1 4 13 16 33 37 41 44 51 54 61 64 71 74 87 91 94 103]
                     Texture: [0x0 GraphicsPlaceholder]
            TwoSidedLighting: 'off'
                  VertexData: [3x102 single]
               VertexIndices: []
                     Visible: 'on'
</pre>
<p>But how did I know these properties existed? The easiest way in this case would be to use my <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties"><i><b>getundoc</b></i> utility</a>, but we could also use my <a target="_blank" href="/articles/uiinspect"><i><b>uiinspect</b></i> utility</a> or even the plain-ol&#8217; <a target="_blank" href="/articles/accessing-private-object-properties"><i><b>struct</b></i> function</a>.<br />
<i>p.s. &#8211; there&#8217;s an alternative way, using the Java bean adapter that is associated with each Matlab graphics object: <code>java(hContour)</code>. Specifically, this object apparent has the public method <code>browseableChildren(java(hContour))</code> which returns the list of all children (in our case, 41 text labels [bean adapters], 20 lines, and a single object holding a <code>ListOfPointsHighlight</code> that corresponds to the regular hidden <b>SelectionHandle</b> property). However, I generally dislike working with the bean adapters, especially when there&#8217;s a much &#8220;cleaner&#8221; way to get these objects, in this case using the regular <b>EdgePrims</b>, <b>FacePrims</b>, <b>TextPrims</b> and <b>SelectionHandle</b> properties. Readers who are interested in Matlab internals can explore the bean adapters using a combination of my <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties"><b>getundoc</b></a> and <a target="_blank" href="/articles/uiinspect"><b>uiinspect</b></a> utilities.</i><br />
So far for the easy part. Now for some more challenging questions:</p>
<h3 id="color">Customizing the color</h3>
<p>First, can we modify the contour fill to have a semi- (or fully-) transparent fill color? &#8211; indeed we can:</p>
<pre lang='matlab'>
[~, hContour] = contourf(peaks(20), 10);
drawnow;  % this is important, to ensure that FacePrims is ready in the next line!
hFills = hContour.FacePrims;  % array of TriangleStrip objects
[hFills.ColorType] = deal('truecoloralpha');  % default = 'truecolor'
for idx = 1 : numel(hFills)
   hFills(idx).ColorData(4) = 150;   % default=255
end
</pre>
<p><center><figure style="width: 420px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Contour plot in HG2, with and without transparency" src="https://undocumentedmatlab.com/images/hg2-contourf-animated.gif" title="Contour plot in HG2, with and without transparency" width="420" height="300" /><figcaption class="wp-caption-text">Contour plot in HG2, with and without transparency</figcaption></figure></center><br />
Similar transparency effects can also be applied to the <code>LineStrip</code> and <code>Text</code> objects. A discussion of the various combinations of acceptable color properties <a target="_blank" href="/articles/customizing-axes-rulers#Axle">can be found here</a>.</p>
<h3 id="mouse">Mouse clicks</h3>
<p>Next, how can we set a custom context-menu for individual labels and contour lines?<br />
Unfortunately, <code>Text</code>, <code>LineStrip</code> and <code>TriangleStrip</code> objects do not posses a <b>ButtonDownFcn</b> or <b>UIContextMenu</b> property, not even hidden. I tried searching in the internal/undocumented properties, but nothing came up.</p>
<h5 id="mouse1">Mouse click solution #1</h5>
<p>So the next logical step would be to trap the mouse-click event at the contour object level. We cannot simply click the contour and check the clicked object because that would just give us the <code>hContour</code> object handle rather than the individual <code>Text</code> or <code>LineStrip</code>. So the idea would be to set <code>hContour.HitTest='off'</code>, in the hope that the mouse click would be registered on the graphic object directly beneath the mouse cursor, namely the label or contour line. It turns out that the labels&#8217; and lines&#8217; <b>HitTest</b> property is &#8216;off&#8217; by default, so, we also need to set them all to &#8216;on&#8217;:</p>
<pre lang='matlab'>
hContour.HitTest = 'off';
[hContour.TextPrims.HitTest] = deal('on');
[hContour.EdgePrims.HitTest] = deal('on');
[hContour.FacePrims.HitTest] = deal('on');
hContour.ButtonDownFcn = @(h,e)disp(struct(e));
</pre>
<p>This seemed simple enough, but failed spectacularly: it turns out that because <code>hContour.HitTest='off'</code>, mouse clicks are not registered on this objects, and on the other hand we cannot set the <b>ButtonDownFcn</b> on the primitive objects because they don&#8217;t have a <b>ButtonDownFcn</b> property!<br />
Who said life is easy?<br />
One workaround is to set the figure&#8217;s <b>WindowButtonDownFcn</b> property:</p>
<pre lang='matlab'>set(gcf, 'WindowButtonDownFcn', @myMouseClickCallback);</pre>
<p>Now, inside your <code>myMouseClickCallback</code> function you can check the clicked object. We could use the undocumented builtin <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/239883#613421"><i><b>hittest</b>(hFig)</i> function</a> to see which object was clicked. Alternatively, we could use the callback <code>eventData</code>&#8216;s undocumented <b>HitObject</b>/<b>HitPrimitive</b> properties (this variant does not require the <b>HitTest</b> property modifications above):</p>
<pre lang='matlab'>
function myMouseClickCallback(hFig, eventData)
   hitPrimitive = hittest(hFig);  % undocumented function
   hitObject    = eventData.HitObject;     % undocumented property => returns a Contour object (=hContour)
   hitPrimitive = eventData.HitPrimitive;  % undocumented property => returns a Text or LineStrip object
   hitPoint     = eventData.Point;         % undocumented property => returns [x,y] pixels from figure's bottom-left corner
   if strcmpi(hFig.SelectionType,'alt')  % right-click
      if isa(hitPrimitive, 'matlab.graphics.primitive.world.Text')  % label
         displayTextContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.LineStrip')  % contour line
         displayLineContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.TriangleStrip')  % contour fill
         displayFillContextMenu(hitPrimitive, hitPoint)
      else
         ...
      end
   end
end
</pre>
<h5 id="mouse2">Mouse click solution #2</h5>
<p>A totally different solution is to keep the default <code>hContour.HitTest='on'</code> (and the primitives&#8217; as &#8216;off&#8217;) and simply query the contour object&#8217;s <b>ButtonDownFcn</b> callback&#8217;s <code>eventData</code>&#8216;s undocumented <b>Primitive</b> property:</p>
<pre lang='matlab'>hContour.ButtonDownFcn = @myMouseClickCallback;</pre>
<p>And in the callback function:</p>
<pre lang='matlab'>
function myMouseClickCallback(hContour, eventData)
   hitPrimitive = eventData.Primitive;  % undocumented property => returns a Text or LineStrip object
   hitPoint     = eventData.IntersectionPoint;  % [x,y,z] in data units
   hFig = ancestor(hContour, 'figure');
   if strcmpi(hFig.SelectionType,'alt')  % right-click
      if isa(hitPrimitive, 'matlab.graphics.primitive.world.Text')  % label
         displayTextContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.LineStrip')  % contour line
         displayLineContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.TriangleStrip')  % contour fill
         displayFillContextMenu(hitPrimitive, hitPoint)
      else
         ...
      end
   end
end
</pre>
<p><a target="_blank" href="/articles/adding-context-menu-to-uitree">This article</a> should be a good start in how to code the <code>displayTextContextMenu</code> etc. functions to display a context menu.</p>
<h3 id="reset">Customizations reset</h3>
<p>Finally, there are apparently numerous things that cause our customized labels and lines to reset to their default appearance: resizing, updating contour properties etc. To update the labels in all these cases in one place, simply listen to the undocumented <a target="_blank" href="/articles/undocumented-hg2-graphics-events"><code>MarkedClean</code> event</a>:</p>
<pre lang='matlab'>addlistener(hContour, 'MarkedClean', @updateLabels);</pre>
<p>Where <code>updateLabels</code> is a function were you set all the new labels.</p>
<h3 id="future">Prediction about forward compatibility</h3>
<p>I am marking this article as &#8220;<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>&#8220;, not because of the basic functionality (being important enough I don&#8217;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&#8217;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&#8217;t exist, perhaps they still exist and simply have different names.<br />
<u><b>Addendum November 11, 2017</b></u>: The <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> properties have still not changed their names and functionality. I explained a nice use for them in <a href="/articles/customizing-contour-plots-part2" target="_blank">a followup post</a>, explaining how we can modify the contour labels to have different font sizes and the same colors as their corresponding contour lines.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots">Customizing contour 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-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-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/hidden-hg2-plot-functionality" rel="bookmark" title="Accessing hidden HG2 plot functionality">Accessing hidden HG2 plot functionality </a> <small>In HG2, some of the plot functionality is hidden in undocumented properties. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-contour-plots/feed</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Using linkaxes vs. linkprop</title>
		<link>https://undocumentedmatlab.com/articles/using-linkaxes-vs-linkprop?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-linkaxes-vs-linkprop</link>
					<comments>https://undocumentedmatlab.com/articles/using-linkaxes-vs-linkprop#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 22 Jul 2015 20:30:04 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5928</guid>

					<description><![CDATA[<p>linkaxes has a built-in limitation, so using linkprop may sometimes be beneficial. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-linkaxes-vs-linkprop">Using linkaxes vs. linkprop</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/determining-axes-zoom-state" rel="bookmark" title="Determining axes zoom state">Determining axes zoom state </a> <small>The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object....</small></li>
<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-performance" rel="bookmark" title="Plot performance">Plot performance </a> <small>Undocumented inner plot mechanisms can significantly improve plotting performance ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>One of my clients recently asked me to solve a very peculiar problem: He had several axes and was using Matlab&#8217;s builtin <i><b>linkaxes</b></i> function to link their axis limits. However, it didn&#8217;t behave quite the way that he expected. His axes were laid out as 2&#215;2 subplots, and he wanted the two columns to be independently linked in the X axis, and the two rows to be independently linked in the Y axis:</p>
<pre lang='matlab'>
% Prepare the axes
ax(1,1) = subplot(2,2,1);
ax(1,2) = subplot(2,2,2);
ax(2,1) = subplot(2,2,3);
ax(2,2) = subplot(2,2,4);
% Plot something
x = 0 : 0.01 : 10;
line(x, sin(x),   'Parent',ax(1,1));
line(x, sin(2*x), 'Parent',ax(1,2));
line(x, cos(x),   'Parent',ax(2,1));
line(x, cos(5*x), 'Parent',ax(2,2));
% Link the relevant axes
linkaxes(ax(:,1),'x');  % left column
linkaxes(ax(:,2),'x');  % right column
linkaxes(ax(1,:),'y');  % top row
linkaxes(ax(2,:),'y');  % bottom row
</pre>
<p>The problem was that the plots didn&#8217;t behave as expected: when zooming in on the bottom-left axes, for example, only the bottom-right axes was updated (Y-limits synced), whereas the top-left axes&#8217; X-limits remained unchanged:<br />
<center><figure style="width: 478px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Badly-synced axes limits" src="https://undocumentedmatlab.com/images/linkaxes_bad.gif" title="Badly-synced axes limits" width="478" height="374" /><figcaption class="wp-caption-text">Badly-synced axes limits</figcaption></figure></center><br />
<span id="more-5928"></span><br />
Apparently, the second set of two <i><b>linkaxes</b></i> commands (to sync the rows&#8217; Y-limits) overrode the first set of two <i><b>linkaxes</b></i> commands (to sync the columns&#8217; X-limits).</p>
<h3 id="analysis">Analysis</h3>
<p>The reason for this unexpected behavior is that under the hood, <i><b>linkaxes</b></i> attaches property-change listeners to the corresponding axes, and stores these listeners in the axes&#8217; hidden <b>ApplicationData</b> property (which is typically accessible via the <i><b>getappdata / setappdata / isappdata / rmappdata</b></i> set of functions). Specifically, up to a certain Matlab release (R2013b?), the listeners were placed in a field called &#8216;listener__&#8217;, and since then in a field called &#8216;graphics_linkaxes&#8217;. In either case, the field name was constant.<br />
Therefore, when we placed the first set of <i><b>linkaxes</b></i> commands, the axes were correctly synced vertically (ax(1,1) with ax(2,1) in their X-limits, and similarly ax(1,2) with ax(2,2)). But when we placed the second set of <i><b>linkaxes</b></i> commands, the internal field in the axes&#8217; <b>ApplicationData</b> property was overriden with the new listeners (that synced the rows&#8217; Y-limits).<br />
It so happens that Matlab listeners have a very nasty feature of being deleted when they are no longer referenced anywhere (within a workspace variable or object property). So when we overrode the first set of listener handles, we effectively deleted them, as if they were never set in the first place.<br />
Some people may possibly complain about both issues at this point:</p>
<ul>
<li>That Matlab listeners get deleted so easily without so much as a console warning, and certainly against naive intuition.</li>
<li>That repeated calls to <i><b>linkaxes</b></i> should override (rather than complement) each other.</li>
</ul>
<p>As a side note, the <i><b>addlistener</b></i> function creates a listener and then persists it in the object&#8217;s hidden <b>AutoListeners__</b> property. However, unlike the <i><b>linkaxes</b></i> behavior, <i><b>addlistener</b></i>&#8216;s listener handles are always appended to <b>AutoListeners__</b>&#8216;s contents, rather than replacing it. This ensures that all listeners are accessible and active until their container is deleted or they are specifically modified/removed. I wish that <i><b>linkaxes</b></i> used this mechanism, rather than its current <b>ApplicationData</b> one.</p>
<h3 id="linkprop">Workaround: <i>linkprop</i></h3>
<p>Luckily, there is a very easy and simple workaround, namely to use <i><b>linkprop</b></i> rather than <i><b>linkaxes</b></i>. The <i><b>linkprop</b></i> function is a lower-level function that creates a property-change listener that syncs corresponding properties in any specified array of object handles. In fact, <i><b>linkaxes</b></i> uses <i><b>linkprop</b></i> in order to create the necessary listeners. In our case, we can use <i><b>linkprop</b></i> directly, to independently attach such listeners to the axes&#8217; <b>XLim</b> and <b>YLim</b> properties. We just need to ensure that all these listeners remain accessible to Matlab throughout the corresponding objects&#8217; life-cycle. This is easily done using <b>ApplicationData</b>, as is done by <i>linkaxes.m</i> but in a smarter manner that does not override the previous values. The benefit of this is that when the axes are deleted, then so are the listeners; as long as the axes are accessible then so are the listeners. We just need to ensure that we don&#8217;t override these listener values:</p>
<pre lang='matlab'>
setappdata(ax(1,1), 'YLim_listeners', linkprop(ax(1,:),'YLim'));
setappdata(ax(2,1), 'YLim_listeners', linkprop(ax(2,:),'YLim'));
setappdata(ax(1,1), 'XLim_listeners', linkprop(ax(:,1),'XLim'));
setappdata(ax(1,2), 'XLim_listeners', linkprop(ax(:,2),'XLim'));
</pre>
<p>This results in the expected behavior:<br />
<center><figure style="width: 478px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="properly-linked axes" src="https://undocumentedmatlab.com/images/linkaxes.gif" title="properly-linked axes" width="478" height="374" /><figcaption class="wp-caption-text">properly-linked axes</figcaption></figure></center></p>
<h3 id="conclusions">Conclusions</h3>
<p>The design decision by MathWorks to automatically delete Matlab listeners as soon as their reference count is zeroed and they get garbage-collected, causes a myriad of unexpected run-time behaviors, one of which is exemplified in today&#8217;s post on <i><b>linkaxes</b></i>. This would still have not caused any problem had the developers of <i><b>linkaxes</b></i> been aware of this listener feature and taken care to store the linked listener handles in an accumulating repository (e.g., adding the listener handle to an array of existing handles, rather than replacing a scalar handle).<br />
Luckily, now that we know how Matlab listeners behave, we can easily identify abnormal behavior that results from listener handles going out of scope, and can easily take steps to persist the handles somewhere, so that they will remain active.<br />
I wish to stress here that the listeners&#8217; limited scope is fully documented in several places in the documentation (e.g., <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/matlab_oop/listener-lifecycle.html#brc3z4h">here</a> as well as the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/linkprop.html#zmw57dd0e386862"><i><b>linkprop</b></i> doc page</a>). The non-additive behavior of <i><b>linkaxes</b></i> is also documented, albeit in an <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/linkaxes.html#moreabout">almost-invisible footnote</a> on its doc-page.<br />
However, I humbly contend that the fact that these behaviors are documented doesn&#8217;t meant that they are <i>correct</i>. After all, figure windows or timers aren&#8217;t deleted when their handle goes out of scope, are they? At the very least, I hope that MathWorks will improve the relevant doc pages, to highlight these non-intuitive behaviors, and in the case of <i><b>linkaxes</b></i> to present a <i><b>linkprop</b></i> usage example as a workaround.<br />
If you are interested in the topic of Matlab listeners, note that I&#8217;ve written quite a few listener-related posts over the years (about property-change listeners as well as event listeners). I urge you to take a look at the list of related articles presented below, or to use the search box at the top of the page.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-linkaxes-vs-linkprop">Using linkaxes vs. linkprop</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/determining-axes-zoom-state" rel="bookmark" title="Determining axes zoom state">Determining axes zoom state </a> <small>The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object....</small></li>
<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-performance" rel="bookmark" title="Plot performance">Plot performance </a> <small>Undocumented inner plot mechanisms can significantly improve plotting performance ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/using-linkaxes-vs-linkprop/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented view transformation matrix</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-view-transformation-matrix?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-view-transformation-matrix</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-view-transformation-matrix#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 15 Apr 2015 21:21:51 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></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=5711</guid>

					<description><![CDATA[<p>Matlab's view function returns an undocumented output transformation matrix.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-view-transformation-matrix">Undocumented view transformation matrix</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/matrix-processing-performance" rel="bookmark" title="Matrix processing performance">Matrix processing performance </a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/ishghandle-undocumented-input-parameter" rel="bookmark" title="ishghandle&#039;s undocumented input parameter">ishghandle&#039;s undocumented input parameter </a> <small>The built-in function ishghandle accepts a second input argument with the expected handle type....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties" rel="bookmark" title="getundoc &#8211; get undocumented object properties">getundoc &#8211; get undocumented object properties </a> <small>getundoc is a very simple utility that displays the hidden (undocumented) properties of a specified handle object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types" rel="bookmark" title="Undocumented plot marker types">Undocumented plot marker types </a> <small>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Everyone knows Matlab&#8217;s <i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/view.html">view</a></b></i> function, right? You know, the function that can set a 3D plot to the proper orientation angles and/or return the current plot&#8217;s azimuth/elevation angles. I&#8217;ve used it numerous times myself in the past two decades. It&#8217;s one of Matlab&#8217;s earliest functions, dating back to at least 1984. Still, as often as I&#8217;ve used it, it was not until I came across <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/340301">Bruce Elliott&#8217;s post on CSSM</a> last week that I realized that this seamingly-innocent stock Matlab function holds a few interesting secrets.</p>
<h3 id="view">view()&#8217;s transformation matrix output</h3>
<p>First, while <i><b>view</b></i>&#8216;s 2-output syntax (<code>[az,el]=view()</code>) is well known and documented, there is also a single-output syntax (<code>T=view()</code>) that is neither. To be exact, this syntax is not mentioned in the official documentation pages, but it <i>does</i> appear in the help section of <i>view.m</i>, which is viewable (no pun intended&#8230;) if you type the following in your Matlab console (R2014a or earlier, note the highlighted lines):<br />
<span id="more-5711"></span></p>
<pre lang='matlab' highlight='24,28'>
>> help view
 view   3-D graph viewpoint specification.
    view(AZ,EL) and view([AZ,EL]) set the angle of the view from which an
    observer sees the current 3-D plot.  AZ is the azimuth or horizontal
    rotation and EL is the vertical elevation (both in degrees). Azimuth
    revolves about the z-axis, with positive values indicating counter-
    clockwise rotation of the viewpoint. Positive values of elevation
    correspond to moving above the object; negative values move below.
    view([X Y Z]) sets the view angle in Cartesian coordinates. The
    magnitude of vector X,Y,Z is ignored.
    Here are some examples:
    AZ = -37.5, EL = 30 is the default 3-D view.
    AZ = 0, EL = 90 is directly overhead and the default 2-D view.
    AZ = EL = 0 looks directly up the first column of the matrix.
    AZ = 180 is behind the matrix.
    view(2) sets the default 2-D view, AZ = 0, EL = 90.
    view(3) sets the default 3-D view, AZ = -37.5, EL = 30.
    [AZ,EL] = view returns the current azimuth and elevation.
    T = view returns the current general 4-by-4 transformation matrix.
    view(AX,...) uses axes AX instead of the current axes.
    See also viewmtx, the axes Properties view, Xform.
    Reference page in Help browser
       doc view
>> surf(peaks); T=view
T =
      0.79335     -0.60876            0    -0.092296
      0.30438      0.39668      0.86603     -0.78354
       0.5272      0.68706         -0.5       8.3031
            0            0            0            1
</pre>
<p>Note that the extra highlighted information is probably a documentation oversight by some MathWorker many years ago, since it was removed from the help section in R2014b and does not appear in the doc pages (not even in R2014a). Perhaps it was documented in the early years but then someone for who-knows-what-reason decided that it shouldn&#8217;t be, and then forgot to remove all the loose ends until R2014b. Or maybe it was this way from the very beginning, I don&#8217;t know.<br />
In any case, just to be clear on this, the transformation matrix out is still returned by <i><b>view</b></i> in the latest Matlab release (R2015a), just as it has for the past who-knows-how-many releases.<br />
There are several interesting things to note here:</p>
<h3 id="viewmtx">view()&#8217;s vs. viewmtx()&#8217;s transformation matrices</h3>
<p>First, MathWorks have still not done a good job of removing all loose ends. Specifically, the <code>T=view</code> syntax is discussed in the doc page (and help section) of the <i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/viewmtx.html">viewmtx</a></b></i> function.<br />
To make things worse (and even more confusing), the usage example shown in that doc page is wrong: it says that <code>view(az,el); T=view</code> returns the same transformation matrix T as <code>T=viewmtx(az,el)</code>. Close, but not the same:</p>
<pre lang='matlab'>
>> view(30,60); T=view
T =
      0.86603          0.5            0     -0.68301
     -0.43301         0.75          0.5     -0.40849
        -0.25      0.43301     -0.86603       9.0018
            0            0            0            1
>> T2=viewmtx(30,60)
T2 =
      0.86603          0.5            0            0
     -0.43301         0.75          0.5            0
         0.25     -0.43301      0.86603            0
            0            0            0            1
</pre>
<p>Tough luck I guess for anyone who relies on <i><b>viewmtx</b></i>&#8216;s output for complex 3D graphics&#8230;<br />
T and T2 appear to be related via a transformation matrix (XT=[1,0,0,0; 0,1,0,0; 0,0,-1,0; 0,0,0,1], we&#8217;ll use it again below) that fixes the signs of the first 3 columns, and another translation matrix (camera viewpoint?) that provides the 4th column of T.</p>
<h3 id="HG1">HG1&#8217;s undocumented axes transformation properties</h3>
<p>Another tidbit that should never have been placed in <i><b>view</b></i>&#8216;s help section in the first place, is the reference to the axes property <b>Xform</b> (read: &#8220;transform&#8221;, not &#8220;X-Form&#8221;). <b>Xform</b> is a hidden undocumented property, and as far as I can tell has always been this way. It is therefore surprising to see it mentioned in the official help section of a highly-visible function such as <i><b>view</b></i>. In fact, I don&#8217;t remember any other similar case.<br />
In HG1 (R2014a and earlier), the axes&#8217; <b>Xform</b> property held the transformation matrix that <i><b>view</b></i> returns. Alongside <b>Xform</b>, the HG1 axes contained several additional transformation vectors (<b>x_RenderOffset, x_RenderScale</b>) and matrices (<b>x_NormRenderTransform, x_ProjectionTransform, x_RenderTransform, x_ViewPortTransform, x_ViewTransform</b> &#8211; the latter (x_ViewTransform) is the same as <b>Xform</b>) that could be used for various purposes (<a target="_blank" rel="nofollow" href="https://groups.google.com/d/msg/comp.soft-sys.matlab/bOSDB_chCkw/res_spSLSicJ">example</a>, <a target="_blank" rel="nofollow" href="https://lists.gnu.org/archive/html/octave-maintainers/2010-11/msg00087.html">technical details</a>). All of these properties were removed in HG2 (R2014b or newer).<br />
A complete usage example for some of these properties can be found in MathWorker Joe Conti&#8217;s <i><b>select3d</b></i> utility, which was <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/1241-select3d-m--select3dtool-m">removed from the File exchange</a>, <a target="_blank" rel="nofollow" href="https://github.com/justingardner/mrTools/blob/master/mrUtilities/ImageProcessing/select3d.m">but can still be found online</a> (note that it croacks on HG2=R2014b+ due to the removal of the hidden properties):</p>
<pre lang='matlab'>
function [p] = local_Data2PixelTransform(ax,vert)
% Transform vertices from data space to pixel space.
% Get needed transforms
xform  = get(ax,'x_RenderTransform');
offset = get(ax,'x_RenderOffset');
scale  = get(ax,'x_RenderScale');
% Equivalent: nvert = vert/scale - offset;
nvert(:,1) = vert(:,1)./scale(1) - offset(1);
nvert(:,2) = vert(:,2)./scale(2) - offset(2);
nvert(:,3) = vert(:,3)./scale(3) - offset(3);
% Equivalent xvert = xform*xvert;
w = xform(4,1) * nvert(:,1) + xform(4,2) * nvert(:,2) + xform(4,3) * nvert(:,3) + xform(4,4);
xvert(:,1) = xform(1,1) * nvert(:,1) + xform(1,2) * nvert(:,2) + xform(1,3) * nvert(:,3) + xform(1,4);
xvert(:,2) = xform(2,1) * nvert(:,1) + xform(2,2) * nvert(:,2) + xform(2,3) * nvert(:,3) + xform(2,4);
% w may be 0 for perspective plots
ind = find(w==0);
w(ind) = 1; % avoid divide by zero warning
xvert(ind,:) = 0; % set pixel to 0
p(:,1) = xvert(:,1) ./ w;
p(:,2) = xvert(:,2) ./ w;
</pre>
<p>We could even set these hidden properties directly, as Bruno Luong <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/253563">showed</a> back in 2009 (the bug he reported in the R2009b prerelease was temporary, it still worked ok in R2014a):</p>
<pre lang='matlab'>set(gca,'Xform',eye(4))</pre>
<h3 id="HG2">HG2&#8217;s transformations</h3>
<p>In HG2 (R2014b onward), we no longer have access to the hidden properties above. I&#8217;m still not exactly sure how to get all the transformations above, but at least the following can be used to replicate the transformation matrix T:</p>
<pre lang='matlab'>
% "standard" way to get the transformation matrix
T = view;
% internal way
XT = [1,0,0,0; 0,1,0,0; 0,0,-1,0; 0,0,0,1];
hCamera = get(gca, 'Camera');
T = XT * GetViewMatrix(hCamera);
</pre>
<p>I&#8217;m guessing there are probably similar ways to get the other transformation matrices, but I&#8217;ll leave that as an exercise to the reader. Anyone who is up to the task is welcome to leave a comment below. Don&#8217;t come asking for my help here &#8211; I&#8217;m off to solve another puzzle. After all, there&#8217;s only a week left before my next blog post is due, so I better get started.<br />
In summary, MathWorks have apparently done some cleanup for the new HG2 in R2014b, but I guess there&#8217;s still some work left to do (at least on the documentation). More importantly, much more work is needed to provide simple documented/supported ways of doing 3D transformations without banging our heads at all these hidden corners. Or maybe there already is such a way and I&#8217;m simply not aware of it, there&#8217;s always that possibility&#8230; </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-view-transformation-matrix">Undocumented view transformation matrix</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/matrix-processing-performance" rel="bookmark" title="Matrix processing performance">Matrix processing performance </a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/ishghandle-undocumented-input-parameter" rel="bookmark" title="ishghandle&#039;s undocumented input parameter">ishghandle&#039;s undocumented input parameter </a> <small>The built-in function ishghandle accepts a second input argument with the expected handle type....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties" rel="bookmark" title="getundoc &#8211; get undocumented object properties">getundoc &#8211; get undocumented object properties </a> <small>getundoc is a very simple utility that displays the hidden (undocumented) properties of a specified handle object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types" rel="bookmark" title="Undocumented plot marker types">Undocumented plot marker types </a> <small>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-view-transformation-matrix/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing Matlab uipanels</title>
		<link>https://undocumentedmatlab.com/articles/customizing-matlab-uipanels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-matlab-uipanels</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-matlab-uipanels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 25 Feb 2015 12:24:50 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Icons]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[uipanel]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5595</guid>

					<description><![CDATA[<p>Matlab uipanel controls can be customized using Java in ways that are impossible with plain Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-matlab-uipanels">Customizing Matlab uipanels</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-uicontrol-border" rel="bookmark" title="Customizing uicontrol border">Customizing uicontrol border </a> <small>Matlab uicontrol borders can easily be modified - this article shows how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-matlab-labels" rel="bookmark" title="Customizing Matlab labels">Customizing Matlab labels </a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-uipanels" rel="bookmark" title="Transparent uipanels">Transparent uipanels </a> <small>Matlab uipanels can be made transparent, for very useful effects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-editboxes" rel="bookmark" title="Customizing editboxes">Customizing editboxes </a> <small>Matlab's editbox can be customized in many useful manners...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>The major innovation in Matlab release R2014b was the introduction of the new handle-based graphics system (<a target="_blank" href="/articles/hg2-update">HG2</a>). However, this release also included a few other improvements to graphics/GUI that should not be overlooked. The most notable is that <i><b>uitab</b></i>s are finally officially documented/supported, following a decade or being undocumented (well, undocumented in the official sense, since I took the time to document this functionality in <a target="_blank" href="/articles/tab-panels-uitab-and-relatives">this blog</a> and in my <a target="_blank" href="/books/matlab-java">Matlab-Java book</a>).<br />
A less-visible improvement occurred with <i><b>uipanel</b></i>s: Panels are very important containers when designing GUIs. They enable a visual grouping of related controls and introduce order to an otherwise complex GUI. Unfortunately, until R2014b panels were drawn at the canvas level, and did not use a standard Java Swing controls like other uicontrols. This made it impossible to customize <i><b>uipanel</b></i>s in a similar manner to other GUI uicontrols (<a target="_blank" href="/articles/button-customization">example</a>).<br />
In R2014b, <i><b>uipanel</b></i>s have finally become standard Java Swing controls, a <code>com.mathworks.hg.peer.ui.UIPanelPeer$UIPanelJPanel</code> component that extends Swing&#8217;s standard <code><a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JPanel.html">javax.swing.JPanel</a></code> and Matlab&#8217;s ubiquitous <code>com.mathworks.mwswing.MJPanel</code>. This means that we can finally customize it in various ways that are not available in plain Matlab.<br />
We start the discussion with a simple Matlab code snippet. It is deliberately simple, since I wish to demonstrate only the panel aspects:</p>
<pre lang='matlab'>
figure('Menubar','none', 'Color','w');
hPanel = uipanel('Title','Panel title', 'Units','norm', 'Pos',[.1,.1,.6,.7]);
hButton = uicontrol('String','Click!', 'Parent',hPanel);
</pre>
<p><center><figure style="width: 175px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Standard Matlab uipanel" src="https://undocumentedmatlab.com/images/uipanel1.gif" title="Standard Matlab uipanel" width="175" height="140" /><figcaption class="wp-caption-text">Standard Matlab <i><b>uipanel</b></i></figcaption></figure></center><br />
Notice the default &#8216;etchedin&#8217; panel border, which I hate (note the broken edges at the corners). Luckily, Swing includes a <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/border.html">wide range of alternative borders</a> that we can use. I&#8217;ve already <a target="_blank" href="/articles/customizing-uicontrol-border">demonstrated</a> customizing Matlab uicontrols with Java borders back in 2010 (has it really been that long? wow!). In R2014b we can finally do something similar to <i><b>uipanel</b></i>s:<br />
<span id="more-5595"></span><br />
The first step is to get the <i><b>uipanel</b></i>&#8216;s underlying Java component&#8217;s reference. We can do this using my <a target="_blank" href="/articles/findjobj-find-underlying-java-object"><i><b>findjobj</b></i> utility</a>, but in the specific case of <i><b>uipanel</b></i> we are lucky to have a direct shortcut by using the panel&#8217;s undocumented hidden property <b>JavaFrame</b> and its <b>PrintableComponent</b> property:</p>
<pre lang='matlab'>
>> jPanel = hPanel.JavaFrame.getPrintableComponent
jPanel =
com.mathworks.hg.peer.ui.UIPanelPeer$UIPanelJPanel[,0,0,97x74,...]
</pre>
<p>Let&#8217;s now take a look at the <code>jPanel</code>&#8216;s border:</p>
<pre lang='matlab'>
>> jPanel.getBorder
ans =
com.mathworks.hg.peer.ui.borders.TitledBorder@25cd9b97
>> jPanel.getBorder.get
                Border: [1x1 com.mathworks.hg.peer.ui.borders.EtchedBorderWithThickness]
          BorderOpaque: 0
                 Class: [1x1 java.lang.Class]
                 Title: 'Panel title'
            TitleColor: [1x1 java.awt.Color]
             TitleFont: [1x1 java.awt.Font]
    TitleJustification: 1
         TitlePosition: 2
</pre>
<p>Ok, simple enough. Let&#8217;s replace the border&#8217;s <code>EtchedBorderWithThickness</code> with something more appealing. We start with a simple red <code><a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/border/LineBorder.html">LineBorder</a></code> having rounded corners and 1px width:</p>
<pre lang='matlab'>
jColor = java.awt.Color.red;  % or: java.awt.Color(1,0,0)
jNewBorder = javax.swing.border.LineBorder(jColor, 1, true);  % red, 1px, rounded=true
jPanel.getBorder.setBorder(jNewBorder);
jPanel.repaint;  % redraw the modified panel
</pre>
<p><center><figure style="width: 175px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Rounded-corners LineBorder" src="https://undocumentedmatlab.com/images/uipanel2.gif" title="Rounded-corners LineBorder" width="175" height="140" /><figcaption class="wp-caption-text">Rounded-corners LineBorder</figcaption></figure></center><br />
Or maybe a thicker non-rounded orange border:</p>
<pre lang='matlab'>
jColor = java.awt.Color(1,0.5,0);
jNewBorder = javax.swing.border.LineBorder(jColor, 3, false);  % orange, 3px, rounded=false
jPanel.getBorder.setBorder(jNewBorder);
jPanel.repaint;  % redraw the modified panel
</pre>
<p><center><figure style="width: 175px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Another LineBorder example" src="https://undocumentedmatlab.com/images/uipanel3.gif" title="Another LineBorder example" width="175" height="140" /><figcaption class="wp-caption-text">Another LineBorder example</figcaption></figure></center><br />
Or maybe a <code><a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/border/MatteBorder.html">MatteBorder</a></code> with colored insets:</p>
<pre lang='matlab'>
jColor = java.awt.Color(0,0.3,0.8);  % light-blue
jNewBorder = javax.swing.border.MatteBorder(2,5,8,11,jColor)  % top,left,bottom,right, color
jPanel.getBorder.setBorder(jNewBorder);
jPanel.repaint;  % redraw the modified panel
</pre>
<p><center><figure style="width: 175px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="MatteBorder with solid insets" src="https://undocumentedmatlab.com/images/uipanel4.gif" title="MatteBorder with solid insets" width="175" height="140" /><figcaption class="wp-caption-text">MatteBorder with solid insets</figcaption></figure></center><br />
<code>MatteBorder</code> can also use an icon (rather than a solid color) to fill the border insets. First, let&#8217;s load the icon. We can either load a file directly from disk, or use one of Matlab&#8217;s standard icons. Here are both of these alternatives:</p>
<pre lang='matlab'>
% Alternative #1: load from disk file
icon = javax.swing.ImageIcon('C:\Yair\star.gif');
% Alternative #2: load a Matlab resource file
jarFile = fullfile(matlabroot,'/java/jar/mlwidgets.jar');
iconsFolder = '/com/mathworks/mlwidgets/graphics/resources/';
iconURI = ['jar:file:/' jarFile '!' iconsFolder 'favorite_hoverover.png'];  % 14x14 px
icon = javax.swing.ImageIcon(java.net.URL(iconURI));
</pre>
<p>We can now pass this icon reference to <code>MatteBorder</code>&#8216;s constructor:</p>
<pre lang='matlab'>
w = icon.getIconWidth;
h = icon.getIconHeight;
jNewBorder = javax.swing.border.MatteBorder(h,w,h,w,icon)  % top,left,bottom,right, icon
jPanel.getBorder.setBorder(jNewBorder);
jPanel.repaint;  % redraw the modified panel
</pre>
<p><center><figure style="width: 175px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="MatteBorder with icon insets" src="https://undocumentedmatlab.com/images/uipanel5.gif" title="MatteBorder with icon insets" width="175" height="140" /><figcaption class="wp-caption-text">MatteBorder with icon insets</figcaption></figure></center><br />
Additional useful Swing borders can be found in the list of classes implementing the <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/border/Border.html"><code>Border</code> interface</a>, or via the <code><a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/BorderFactory.html">BorderFactory</a></code> class. For example, let&#8217;s create a <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/BorderFactory.html#createDashedBorder(java.awt.Paint,%20float,%20float,%20float,%20boolean)">dashed border</a> having a 3-2 ratio between the line lengths and the spacing:</p>
<pre lang='matlab'>
jColor = java.awt.Color.blue;  % or: java.awt.Color(0,0,1);
lineWidth = 1;
relativeLineLength = 3;
relativeSpacing = 2;
isRounded = false;
jNewBorder = javax.swing.BorderFactory.createDashedBorder(jColor,lineWidth,relativeLineLength,relativeSpacing,isRounded);
jPanel.getBorder.setBorder(jNewBorder);
jPanel.repaint;  % redraw the modified panel
</pre>
<p><center><figure style="width: 175px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="StrokeBorder (dashed)" src="https://undocumentedmatlab.com/images/uipanel6.gif" title="StrokeBorder (dashed)" width="175" height="140" /><figcaption class="wp-caption-text">StrokeBorder (dashed)</figcaption></figure></center><br />
After seeing all these possibilities, I think you&#8217;ll agree with me that Matlab&#8217;s standard <i><b>uipanel</b></i> borders look pale in comparison.<br />
Have you used any interesting borders in your Matlab GUI? Or have you customized your panels in some other nifty manner? If so, then please place a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-matlab-uipanels">Customizing Matlab uipanels</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-uicontrol-border" rel="bookmark" title="Customizing uicontrol border">Customizing uicontrol border </a> <small>Matlab uicontrol borders can easily be modified - this article shows how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-matlab-labels" rel="bookmark" title="Customizing Matlab labels">Customizing Matlab labels </a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-uipanels" rel="bookmark" title="Transparent uipanels">Transparent uipanels </a> <small>Matlab uipanels can be made transparent, for very useful effects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-editboxes" rel="bookmark" title="Customizing editboxes">Customizing editboxes </a> <small>Matlab's editbox can be customized in many useful manners...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-matlab-uipanels/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
	</channel>
</rss>
