<?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/tag/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>Matlab toolstrip – part 4 (control customization)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-4-control-customization</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 30 Dec 2018 16:00:00 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8110</guid>

					<description><![CDATA[<p>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization">Matlab toolstrip – part 4 (control customization)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In a <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" target="_blank">previous post</a> I showed how we can create custom Matlab app toolstrips. Toolstrips can be a bit complex to develop so I’m trying to proceed slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">the Toolstrip miniseries</a> before reading this post. In today&#8217;s post we continue the discussion of the toolstrip created in the previous post:<br />
<center><figure style="width: 440px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_basic_controls.png" alt="Toolstrip example (basic controls)" title="Toolstrip example (basic controls)" width="100%" style="max-width:553px; margin:0" /><figcaption class="wp-caption-text">Toolstrip example (basic controls)</figcaption></figure></center><br />
Today&#8217;s post will show how to attach user-defined functionality to toolstrip components, as well as some additional customizations. At the end of today&#8217;s article, you should be able to create a fully-functional custom Matlab toolstrip. <span id="more-8110"></span> Today&#8217;s post will remain within the confines of a Matlab &#8220;app&#8221;, i.e. a tool-group that displays docked figures. Future posts will discuss lower-level toolstrip mechanisms, that enable advanced customizations as well as integration in legacy (Java-based, even GUIDE-created) Matlab figures.</p>
<h3 id="callbacks">Control callbacks</h3>
<p>Controls are useless without settable callbacks that affect the program state based on user interactions. There are two different mechanisms for setting callbacks for Matlab toolstrip controls. Refer to the example in the <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization#example" target="_blank">previous post</a>:</p>
<ol>
<li>Setting the control&#8217;s callback property or properties &#8211; the property names differ across components (no, for some reason it&#8217;s never as simple as <b>Callback</b> in standard uicontrols). For example, the main action callback for push-buttons is <b>ButtonPushedFcn</b>, for toggle-buttons and checkboxes it&#8217;s <b>ValueChangedFcn</b> and for listboxes it&#8217;s <b></b>. Setting the callback is relatively easy:
<pre lang="matlab">
hColorbar.ValueChangedFcn = @toggleColorbar;
function toggleColorbar(hAction,hEventData)
    if hAction.Selected
        colorbar;
    else
        colorbar('off');
    end
end
</pre>
<p>The <code>hAction</code> object that is passed to the callback function as the first input arg contains various fields of interest, but for some reason the most important object property (<b>Value</b>) is renamed as the <b>Selected</b> property (most confusing). Also, a back-reference to the originating control (<code>hColorbar</code> in this example), which is important for many callbacks, is also missing (and no &#8211; I couldn&#8217;t find it in the hidden properties either):</p>
<pre lang="matlab">
>> hAction
hAction =
  Action with properties:
            Description: 'Toggle colorbar display'
                Enabled: 1
               Shortcut: ''
               Selected: 1
        QuickAccessIcon: []
    SelectionChangedFcn: @toggleColorbar
                   Text: 'Colorbar'
        IsInQuickAccess: 0
            ButtonGroup: []
                   Icon: [1×1 matlab.ui.internal.toolstrip.Icon]
>> hEventData
hEventData =
  ToolstripEventData with properties:
    EventData: [1×1 struct]
       Source: [0×0 handle]
    EventName: ''
>> hEventData.EventData
ans =
  struct with fields:
    Property: 'Value'
    NewValue: 1
    OldValue: 0
</pre>
<p>Note that <code>hEventData.Source</code> is an empty handle for some unknown reason.<br />
The bottom line is that to reference the button state using this callback mechanism we need to either:</p>
<ol>
<li>Access <code>hAction</code>&#8216;s <b>Selected</b> property which stands-in for the originating control&#8217;s <b>Value</b> property (this is what I have shown in the short code snippet above)</li>
<li>Access <code>hEventData.EventData</code> and use its reported Property, NewValue and OldValue fields</li>
<li>Pass the originating control handle as an extra (3rd) input arg to the callback function, and then access it from within the callback. For example:
<pre lang="matlab">
hColorbar.ValueChangedFcn = {@toggleColorbar, hColorbar};
function toggleColorbar(hAction,hEventData,hButton)
    if hButton.Value %hAction.Selected
        colorbar;
    else
        colorbar('off');
    end
end
</pre>
</ol>
</li>
<li>As an alternative, we can use the <i><b>addlistener</b></i> function to attach a callback to control events. Practically all toolstrip components expose public events that can be listened-to using this mechanism. In most cases the control&#8217;s callback property name(s) closely follow the corresponding events. For example, for buttons we have the <b>ValueChanged</b> event that corresponds to the <b>ValueChangedFcn</b> property. We can use listeners as follows:
<pre lang="matlab">
hCheckbox.addlistener('ValueChanged',@toggleLogY);
function toggleLogY(hCheckbox,hEventData)
    if hCheckbox.Value, type = 'log'; else, type = 'linear'; end
    set(gca, 'XScale',type, 'YScale',type, 'ZScale',type);
end
</pre>
<p>Note that when we use the <i><b>addlistener</b></i> mechanism to attach callbacks, we don&#8217;t need any of the tricks above &#8211; we get the originating control handle as the callback function&#8217;s first input arg, and we can access it directly.<br />
Unfortunately, we cannot pass extra args to the callback that we specify using <i><b>addlistener</b></i> (this seems like a trivial and natural thing to have, for MathWorks&#8217; attention&#8230;). In other words, <i><b>addlistener</b></i> only accepts a function handle as callback, not a cell array. To bypass this limitation in uicontrols, we typically add the extra parameters to the control&#8217;s <b>UserData</b> or <b>ApplicationData</b> properties (the latter via the <i><b>setappdata</b></i> function). But alas &#8211; toolstrip components have neither of these properties, nor can we add them in runtime (<a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" target="_blank">as with for other GUI controls</a>). So we need to find some other way to pass these extra values, such as using global variables, or making the callback function nested so that it could access the parent function&#8217;s workspace.
</li>
</ol>
<h3 id="props">Additional component properties</h3>
<p>Component text labels, where relevant, can be set using the component&#8217;s <b>Text</b> property, and the tooltip can be set via the <b>Description</b> property. As I noted in my previous post, I believe that this is an unfortunate choice of property names. In addition, components have control-specific properties such as <b>Value</b> (checkboxes and toggle buttons). These properties can generally be modified in runtime, in order to reflect the program state. For example, we can disable/enable controls, and modify their label, tooltip and state depending on the control&#8217;s new state and the program state in general.<br />
The component icon can be set via the <b>Icon</b> property, where available (for example, buttons have an icon, but checkboxes do not). There are several different ways in which we can set this <b>Icon</b>. I will discuss this in detail in the following post; in the meantime you can review the usage examples in the previous post.<br />
There are a couple of additional hidden component properties that seem promising, most notably <b>Shortcut</b> and <b>Mnemonic</b> (the latter (Mnemonic) is also available in <code>Section</code> and <code>Tab</code>, not just in components). Unfortunately, at least as of R2018b these properties do not seem to be connected yet to any functionality. In the future, I would expect them to correspond to keyboard shortcuts and underlined mnemonic characters, as these functionalities behave in standard menu items.</p>
<h3 id="Java">Accessing the underlying Java control</h3>
<p>As long as we&#8217;re not displaying the toolstrip on a browser page (i.e., inside a uifigure or Matlab Online), the toolstrip is basically composed of Java Swing components from the <code>com.mathworks.toolstrip.components</code> package (such as <code>TSButton</code> or <code>TSCheckBox</code>). I will discuss these Java classes and their customizations in a later post, but for now I just wish to show how to access the underlying Java component of any Matlab MCOS control. This can be done using a central registry of toolstrip components (so-called &#8220;widgets&#8221;), which is accessible via the <code>ToolGroup</code>&#8216;s hidden <b>ToolstripSwingService</b> property, and then via each component&#8217;s hidden widget Id. For example:</p>
<pre lang="matlab">
>> widgetRegistry = hToolGroup.ToolstripSwingService.Registry;
>> jButton = widgetRegistry.getWidgetById(hButton.getId)  % get the hButton's underlying Java control
ans =
com.mathworks.toolstrip.components.TSToggleButton[,"Colorbar",layout<>,NORMAL]
</pre>
<p>We can now apply a wide variety of Java-based customizations to the retrieved <code>jButton</code>, as I have shown in many other articles on this website over the past decade.<br />
Another way to access the toolstrip Java component hierarchy is via <code>hToolGroup.Peer.get(tabIndex).getComponent</code>. This returns the top-level Java control representing the tab whose index in <code>tabIndex</code> (0=left-most tab):</p>
<pre lang="matlab">
>> jToolGroup = hToolGroup.Peer;  % or: =hToolGroup.ToolstripSwingService.SwingToolGroup;
>> jDataTab = jToolGroup.get(0).getComponent;  % Get tab #0 (first tab: "Data")
>> jDataTab.list   % The following is abridged for brevity
com.mathworks.toolstrip.impl.ToolstripTabContentPanel[tab0069230a-52b0-4973-b025-2171cd96301b,0,0,831x93,...]
 SectionWrapper(section54fb084c-934d-4d31-9468-7e4d66cd85e5)
  com.mathworks.toolstrip.impl.ToolstripSectionComponentWithHeader[,0,0,241x92,...]
   com.mathworks.toolstrip.components.TSPanel[section54fb084c-934d-4d31-9468-7e4d66cd85e5,,layout<horizontal>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSButton[,"Refresh all",layout<>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSButton[,"Refresh X,Y",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSButton[,"Refresh Y,Z",layout<>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSButton[,"Refresh X",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSButton[,"Refresh Y",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSButton[,"Refresh Z",layout<>,NORMAL]
 SectionWrapper(sectionebd8ab95-fd33-4a3d-8f24-152589713994)
  com.mathworks.toolstrip.impl.ToolstripSectionComponentWithHeader[,0,0,159x92,...]
   com.mathworks.toolstrip.components.TSPanel[sectionebd8ab95-fd33-4a3d-8f24-152589713994,,layout<horizontal>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSCheckBox[,"Axes borders",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSCheckBox[,"Log scaling",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSCheckBox[,"Inverted Y",layout<>,NORMAL]
 SectionWrapper(section01995bfd-61de-490f-aa22-de50bae1af75)
  com.mathworks.toolstrip.impl.ToolstripSectionComponentWithHeader[,0,0,125x92,...]
   com.mathworks.toolstrip.components.TSPanel[section01995bfd-61de-490f-aa22-de50bae1af75,,layout<horizontal>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSToggleButton[,"Legend",layout<>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSLabel[null," ",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSToggleButton[,"Colorbar",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSLabel[null," ",layout<>,NORMAL]
 com.mathworks.mwswing.MJButton[toolstrip.header.collapseButton,808,70,20x20,...]
</pre>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The next post will discuss icons, for both toolstrip controls as well as the ToolGroup app window.<br />
I plan to discuss complex components in subsequent posts. Such components include button-group, drop-down, listbox, split-button, slider, popup form, gallery etc.<br />
Following that, my plan is to discuss toolstrip collapsibility, the ToolPack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures &#8211; not necessarily in this order.<br />
Have I already mentioned that Matlab toolstrips can be a bit complex?<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.<br />
Happy New Year, everyone!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization">Matlab toolstrip – part 4 (control customization)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing contour plots part 2</title>
		<link>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-contour-plots-part2</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 12 Nov 2017 11:03:37 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7149</guid>

					<description><![CDATA[<p>Matlab contour labels' color and font can easily be customized. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2">Customizing contour plots part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-histogram-plots" rel="bookmark" title="Customizing histogram plots">Customizing histogram plots </a> <small>Basic bar charts and histogram plots can be customized in important aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few weeks ago a user posted a question on Matlab&#8217;s Answers forum, asking whether it is possible to <a href="https://www.mathworks.com/matlabcentral/answers/363059-how-do-i-label-a-contour-plot-in-the-same-colors-as-the-contour-lines" rel="nofollow" target="_blank">display contour labels in the same color as their corresponding contour lines</a>. In today&#8217;s post I&#8217;ll provide some insight that may assist users with similar customizations in other plot types.<br />
Matlab does not provide, for reasons that escape my limited understanding, documented access to the contour plot&#8217;s component primitives, namely its contour lines, labels and patch faces. Luckily however, these handles are accessible (in HG2, i.e. R2014b onward) via undocumented hidden properties aptly named <b>EdgePrims</b>, <b>TextPrims</b> and <b>FacePrims</b>, as I explained in a previous post about <a href="/articles/customizing-contour-plots" target="_blank">contour plots customization</a>, two years ago.<br />
Let&#8217;s start with a simple contour plot of the <i><b>peaks</b></i> function:</p>
<pre lang="matlab">
[X,Y,Z] = peaks;
[C,hContour] = contour(X,Y,Z, 'ShowText','on', 'LevelStep',1);
</pre>
<p>The result is the screenshot on the left:<br />
<center><figure style="width: 454px" class="wp-caption aligncenter"><img 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>Customizing axes part 5 &#8211; origin crossover and labels</title>
		<link>https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-axes-part-5-origin-crossover-and-labels</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 27 Jul 2016 17:00:02 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6564</guid>

					<description><![CDATA[<p>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels">Customizing axes part 5 &#8211; origin crossover and labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/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>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-4-additional-properties" rel="bookmark" title="Customizing axes part 4 &#8211; additional properties">Customizing axes part 4 &#8211; additional properties </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>When HG2 graphics was finally released in R2014b, I posted a series of articles about various undocumented ways by which we can customize Matlab&#8217;s new graphic axes: <a href="/articles/customizing-axes-rulers" target="_blank">rulers (axles)</a>, <a href="/articles/customizing-axes-part-2" target="_blank">baseline, box-frame, grid</a>, <a href="/articles/customizing-axes-part-3-backdrop" target="_blank">back-drop</a>, and <a href="/articles/customizing-axes-part-4-additional-properties" rel="nofollow" target="_blank">other aspects</a>. Today I extend this series by showing how we can customize the axes rulers&#8217; crossover location.<br />
<center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Non-default axes crossover location" src="https://undocumentedmatlab.com/images/axes_origin4.png" title="Non-default axes crossover location" width="337" height="306" /><figcaption class="wp-caption-text">Non-default axes crossover location</figcaption></figure></center><br />
<span id="more-6564"></span></p>
<h3 id="documented">The documented/supported stuff</h3>
<p>Until R2015b, we could only specify the axes&#8217; <b>YAxisLocation</b> as <code>'left'</code> (default) or <code>'right'</code>, and <b>XAxisLocation</b> as <code>'bottom'</code> (default) or <code>'top'</code>. For example:</p>
<pre lang="matlab">
x = -2*pi : .01 : 2*pi;
plot(x, sin(x));
hAxis = gca;
hAxis.YAxisLocation = 'left';    % 'left' (default) or 'right'
hAxis.XAxisLocation = 'bottom';  % 'bottom' (default) or 'top'
</pre>
<p><center><figure style="width: 338px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Default axis locations: axes crossover is non-fixed" src="https://undocumentedmatlab.com/images/axes_origin1.png" title="Default axis locations: axes crossover is non-fixed" width="338" height="302" /><figcaption class="wp-caption-text">Default axis locations: axes crossover is non-fixed</figcaption></figure></center><br />
The crossover location is <i>non-fixed</i> in the sense that if we zoom or pan the plot, the axes crossover will remain at the bottom-left corner, which changes its coordinates depending on the X and Y axes limits.<br />
<a href="http://www.mathworks.com/help/matlab/ref/axes-properties.html#property_xaxislocation" rel="nofollow" target="_blank">Since R2016a</a>, we can also specify <code>'origin'</code> for either of these properties, such that the X and/or Y axes pass through the chart origin (0,0) location. For example, move the <b>YAxisLocation</b> to the origin:</p>
<pre lang="matlab">hAxis.YAxisLocation = 'origin';</pre>
<p><center><figure style="width: 338px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Y-axis location at origin: axes crossover at 0 (fixed), -1 (non-fixed)" src="https://undocumentedmatlab.com/images/axes_origin2.png" title="Y-axis location at origin: axes crossover at 0 (fixed), -1 (non-fixed)" width="338" height="306" /><figcaption class="wp-caption-text">Y-axis location at origin: axes crossover at 0 (fixed), -1 (non-fixed)</figcaption></figure></center><br />
And similarly also for <b>XAxisLocation</b>:</p>
<pre lang="matlab">hAxis.XAxisLocation = 'origin';</pre>
<p><center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="X and Y-axis location at origin: axes crossover fixed at (0,0)" src="https://undocumentedmatlab.com/images/axes_origin3.png" title="X and Y-axis location at origin: axes crossover fixed at (0,0)" width="337" height="306" /><figcaption class="wp-caption-text">X and Y-axis location at origin: axes crossover fixed at (0,0)</figcaption></figure></center><br />
The axes crossover location is now fixed at the origin (0,0), so as we move or pan the plot, the crossover location changes its position in the chart area, without changing its coordinates. This functionality has existed in other graphic packages (outside Matlab) for a long time and until now required quite a bit of coding to emulate in Matlab, so I&#8217;m glad that we now have it in Matlab by simply updating a single property value. MathWorks did a very nice job here of dynamically updating the axles, ticks and labels as we pan (drag) the plot towards the edges &#8211; try it out!</p>
<h3 id="undocumented">The undocumented juicy stuff</h3>
<p>So far for the documented stuff. The undocumented aspect is that we are not limited to using the (0,0) origin point as the fixed axes crossover location. We can use any x,y crossover location, using the <b>FirstCrossoverValue</b> property of the axes&#8217; hidden <b>XRuler</b> and <b>YRuler</b> properties. In fact, <b>we could do this since R2014b</b>, when the new HG2 graphics engine was released, not just starting in R2016a!</p>
<pre lang="matlab">
% Set a fixed crossover location of (pi/2,-0.4)
hAxis.YRuler.FirstCrossoverValue = pi/2;
hAxis.XRuler.FirstCrossoverValue = -0.4;
</pre>
<p><center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom fixed axes crossover location at (&pi;/2,-0.4)" src="https://undocumentedmatlab.com/images/axes_origin4.png" title="Custom fixed axes crossover location at (&pi;/2,-0.4)" width="337" height="306" /><figcaption class="wp-caption-text">Custom fixed axes crossover location at (&pi;/2,-0.4)</figcaption></figure></center><br />
For some reason (bug?), setting <b>XAxisLocation</b>/<b>YAxisLocation</b> to &#8216;origin&#8217; has no visible effect in 3D plots, nor is there any corresponding <b>ZAxisLocation</b> property. Luckily, we can set the axes crossover location(s) in 3D plots using <b>FirstCrossoverValue</b> just as easily as for 2D plots. The rulers also have a <b>SecondCrossoverValue</b> property (default = -inf) that controls the Z-axis crossover, as Yaroslav <a href="/articles/customizing-axes-part-5-origin-crossover-and-labels#comment-384290">pointed out</a> in a comment below. For example:</p>
<pre lang="matlab">
N = 49;
x = linspace(-10,10,N);
M = peaks(N);
mesh(x,x,M);
</pre>
<p><center><figure style="width: 442px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Default crossover locations at (-10,&plusmn;10,-10)" src="https://undocumentedmatlab.com/images/axes_origin_3D1.png" title="Default crossover locations at (-10,&plusmn;10,-10)" width="442" height="249" /><figcaption class="wp-caption-text">Default crossover locations at (-10,&plusmn;10,-10)</figcaption></figure></center></p>
<pre lang="matlab">
hAxis.XRuler.FirstCrossoverValue  = 0; % X crossover with Y axis
hAxis.YRuler.FirstCrossoverValue  = 0; % Y crossover with X axis
hAxis.ZRuler.FirstCrossoverValue  = 0; % Z crossover with X axis
hAxis.ZRuler.SecondCrossoverValue = 0; % Z crossover with Y axis
</pre>
<p><center><figure style="width: 390px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom fixed axes crossover location at (0,0,-10)" src="https://undocumentedmatlab.com/images/axes_origin_3D2.png" title="Custom fixed axes crossover location at (0,0,-10)" width="390" height="230" /><figcaption class="wp-caption-text">Custom fixed axes crossover location at (0,0,-10)</figcaption></figure></center></p>
<pre lang="matlab">
hAxis.XRuler.SecondCrossoverValue = 0; % X crossover with Z axis
hAxis.YRuler.SecondCrossoverValue = 0; % Y crossover with Z axis
</pre>
<p><center><figure style="width: 390px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom fixed axes crossover location at (0,0,0)" src="https://undocumentedmatlab.com/images/axes_origin_3D3.png" title="Custom fixed axes crossover location at (0,0,0)" width="390" height="230" /><figcaption class="wp-caption-text">Custom fixed axes crossover location at (0,0,0)</figcaption></figure></center></p>
<h3 id="labels">Labels</h3>
<p>Users will encounter the following unexpected behavior (bug?) when using either the documented <b>*AxisLocation</b> or the undocumented <b>FirstCrossoverValue</b> properties: when setting an x-label (using the <i><b>xlabel</b></i> function, or the internal axes properties), the label moves from the center of the axes (as happens when <b>XAxisLocation</b>=&#8217;top&#8217; or &#8216;bottom&#8217;) to the <i>right</i> side of the axes, where the secondary label (e.g., exponent) usually appears, whereas the secondary label is moved to the left side of the axis:<br />
<center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Unexpected label positions" src="https://undocumentedmatlab.com/images/axes_origin5.png" title="Unexpected label positions" width="337" height="306" /><figcaption class="wp-caption-text">Unexpected label positions</figcaption></figure></center><br />
In such cases, we would expect the labels locations to be reversed, with the main label on the left and the secondary label in its customary location on the right. The exact same situation occurs with the Y labels, where the main label unexpectedly appears at the top and the secondary at the bottom. Hopefully MathWorks will fix this in the next release (it is probably too late to make it into R2016b, but hopefully R2017a). Until then, we can simply switch the strings of the main and secondary label to make them appear at the expected locations:</p>
<pre lang="matlab">
% Switch the Y-axes labels:
ylabel(hAxis, '\times10^{3}');  % display secondary ylabel (x10^3) at top
set(hAxis.YRuler.SecondaryLabel, 'Visible','on', 'String','main y-label');  % main label at bottom
% Switch the X-axes labels:
xlabel(hAxis, '2^{nd} label');  % display secondary xlabel at right
set(hAxis.XRuler.SecondaryLabel, 'Visible','on', 'String','xlabel');  % main label at left
</pre>
<p>As can be seen from the screenshot, there&#8217;s an additional nuisance: the main label appears a bit larger than the axes font size (the secondary label uses the correct font size). This is because by default Matlab uses a 110% font-size for the main axes label, ostensibly to make them stand out. We can modify this default factor using the rulers&#8217; hidden <b>LabelFontSizeMultiplier</b> property (default=1.1). For example:</p>
<pre lang="matlab">
hAxis.YRuler.LabelFontSizeMultiplier = 1;   % use 100% font-size (same as tick labels)
hAxis.XRuler.LabelFontSizeMultiplier = 0.8; % use 80% (smaller than standard) font-size
</pre>
<p>Note: I described the <a href="/articles/customizing-axes-rulers" target="_blank">ruler objects</a> in my first article of the axes series. Feel free to read it for more ideas on customizing the axes rulers.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels">Customizing axes part 5 &#8211; origin crossover and labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/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>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-4-additional-properties" rel="bookmark" title="Customizing axes part 4 &#8211; additional properties">Customizing axes part 4 &#8211; additional properties </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels/feed</wfw:commentRss>
			<slash:comments>13</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</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>Figure keypress modifiers</title>
		<link>https://undocumentedmatlab.com/articles/figure-keypress-modifiers?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=figure-keypress-modifiers</link>
					<comments>https://undocumentedmatlab.com/articles/figure-keypress-modifiers#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 04 Nov 2015 21:19:59 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6059</guid>

					<description><![CDATA[<p>The figure's CurrentModifier property provides a simple and consistent way to retrieve keypress modifiers: alt-, control- and shift-clicks. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/figure-keypress-modifiers">Figure keypress modifiers</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/uicontrol-side-effect-removing-figure-toolbar" rel="bookmark" title="uicontrol side-effect: removing figure toolbar">uicontrol side-effect: removing figure toolbar </a> <small>Matlab's built-in uicontrol function has a side-effect of removing the figure toolbar. This was undocumented until lately. This article describes the side-effect behavior and how to fix it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<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/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>Matlab figures have a documented property called <b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/figure-properties.html#property_selectiontype">SelectionType</a></b> that returns information about keypress modifiers such as <shift> or <control> that were pressed during mouse clicks. Using this property has several drawbacks IMHO:</p>
<ul>
<li>The reported <b>SelectionType</b> value is <code>'extend'</code> for shift-clicks and <code>'alt'</code> for ctrl-clicks, not very intuitive.</li>
<li>There is no support for alt-clicks, which are reported as regular (<code>'normal'</code>) mouse clicks. In fact, <code>'alt'</code> is reported for ctrl-clicks rather than for alt-clicks, which is very confusing.</li>
<li>There is no support for modifier combinations such as ctrl+shift-click. These again are reported as regular (<code>'normal'</code>) mouse clicks.</li>
<li><b>SelectionType</b> is only updated for mouse clicks, not for keyboard clicks. This again is very confusing. To extract the keypress modifier for key-click events we need to get the <b>Modifier</b> property of the key-press event, and this returns a cell-array of strings (e.g., <code>{'shift','control','alt'}</code>). Note that in this case, unlike <b>SelectionType</b>, the modifier names are as expected, alt-clicks is recognised and so are modifier combinations.</li>
</ul>
<pre lang='matlab'>
% Documented: we need to get the modifier data in two different manners
set(gcf, 'WindowButtonDownFcn', @(h,e) disp(get(gcf,'SelectionType')));  % mouse clicks: displays a single string: 'normal','alt','extend' or 'open'
set(gcf, 'WindowKeyPressFcn',   @(h,e) disp(e.Modifier));  % keyboard clicks: displays a cell-array of strings, e.g. {'shift','control','alt'}
</pre>
<p>The inconsistency between the functionality for mouse and keyboard clicks, and the limitations of the <b>SelectionType</b> property, are striking and most annoying. Some might say that it&#8217;s been like this for the past 2 decades so Matlab users have probably gotten used to it by now. But I must admit that after over 2 decades with Matlab I still need to refer to the documentation to figure out the correct behavior. Maybe that&#8217;s because I&#8217;m getting old, or maybe it means that the behavior is indeed not as intuitive as one could hope for.<br />
For this reason, I was very happy to discover several years ago that there was a much simpler, easier and consistent solution, although (alas) undocumented. The trick is to simply query the undocumented hidden figure property <b>CurrentModifier</b>:<span id="more-6059"></span> <b>CurrentModifier</b> is updated during both mouse and keyboard clicks, in the same consistent manner, in both cases returning the same cell-array of strings as the <b>Modifier</b> property of the standard key-press event:</p>
<pre lang='matlab'>
% Undocumented: the following displays a cell-array of strings having a consistent format, e.g. {'shift','control','alt'}
set(gcf, 'WindowButtonDownFcn', @(h,e) disp(get(gcf,'CurrentModifier')));  % mouse clicks
set(gcf, 'WindowKeyPressFcn',   @(h,e) disp(get(gcf,'CurrentModifier')));  % keyboard clicks
</pre>
<p>Checking whether any modifier was pressed becomes trivial:</p>
<pre lang='matlab'>
modifiers = get(gcf,'CurrentModifier');
wasShiftPressed = ismember('shift',   modifiers);  % true/false
wasCtrlPressed  = ismember('control', modifiers);  % true/false
wasAltPressed   = ismember('alt',     modifiers);  % true/false
</pre>
<p>Hurrah for simplicity and consistency!<br />
Note that despite the fact that <b>CurrentModifier</b> is hidden and undocumented, it has existed as-is for many years, and even survived (unchanged) the major transition from HG1 to HG2 in R2014b. This has to mean that MathWorks recognized the importance of <b>CurrentModifier</b> and took the deliberate decision (and associate dev effort) to preserve it. So why wasn&#8217;t this useful property made documented ages ago, or at the very least at the HG2 transition point? I don&#8217;t have a good answer to this riddle.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/figure-keypress-modifiers">Figure keypress modifiers</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/uicontrol-side-effect-removing-figure-toolbar" rel="bookmark" title="uicontrol side-effect: removing figure toolbar">uicontrol side-effect: removing figure toolbar </a> <small>Matlab's built-in uicontrol function has a side-effect of removing the figure toolbar. This was undocumented until lately. This article describes the side-effect behavior and how to fix it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<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/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/figure-keypress-modifiers/feed</wfw:commentRss>
			<slash:comments>6</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>Transparent legend</title>
		<link>https://undocumentedmatlab.com/articles/transparent-legend?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=transparent-legend</link>
					<comments>https://undocumentedmatlab.com/articles/transparent-legend#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 11 Mar 2015 19:43:27 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5617</guid>

					<description><![CDATA[<p>Matlab chart legends are opaque be default but can be made semi- or fully transparent. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparent-legend">Transparent legend</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/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
<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/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/persisting-transparent-colors-in-hg2" rel="bookmark" title="Persisting transparent colors in HG2">Persisting transparent colors in HG2 </a> <small>We can set semi- and fully-transparent colors in HG2 for multiple graphic objects, but making these settings stick is non-trivial. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve been working lately on Matlab program for a client, which attempts to mimic the appearance and behavior of <a target="_blank" rel="nofollow" href="http://www.metatrader4.com">MetaTrader</a> charts, which are extensively used by traders to visualize financial timeseries and analysis indicators.<br />
Such charts are often heavily laden with information, and a legend can be handy to understand the meaning of the various plot lines. Unfortunately, in such heavily-laden charts the legend box typically overlaps the data. We can of course move the legend box around (programmatically or by interactive dragging). But in such cases it might be more useful to have the legend background become semi- or fully-transparent, such that the underlying plot lines would appear beneath the legend:<br />
<center><a target="_blank" href="/images/TechChart_legend_transparent.gif"><img decoding="async" alt="Matlab chart with a semi-transparent legend (click for details)" src="https://undocumentedmatlab.com/images/TechChart_legend_transparent.gif" title="Matlab chart with a semi-transparent legend (click for details)" width="70%" style="max-width: 865px;" /><br />Matlab chart with a semi-transparent legend (click for details)</a></center><br />
<span id="more-5617"></span><br />
A few months ago I <a target="_blank" href="/articles/plot-line-transparency-and-color-gradient">explained</a> the undocumented feature of setting the transparency level of plot lines by simply specifying a fourth numeric (alpha) value to the <b>Color</b> property. Unfortunately, this technique does not work for all graphic objects. For example, setting a 4th (alpha) value to the <b>MarkerFaceColor</b> property results in an error. In the case of legends, setting a 4th (alpha) value to the legend handle&#8217;s <b>Color</b> property does not result in an error, but is simply ignored.<br />
The solution in the case of legends is similar in concept to that of the <b>MarkerFaceColor</b> property, which I <a target="_blank" href="/articles/plot-markers-transparency-and-color-gradient">explained here</a>. The basic idea is to use one of the legend&#8217;s hidden properties (in this case, <b>BoxFace</b>) in order to access the low-level color properties (which I have already explained in previous posts):</p>
<pre lang='matlab'>
>> hLegend = legend(...);
>> hLegend.Color = [0.5, 0.5, 0.5, 0.8];  % should be 20%-transparent gray, but in fact opaque gray
>> hLegend.BoxFace.get
             AmbientStrength: 0.3
             BackFaceCulling: 'none'
                ColorBinding: 'object'
                   ColorData: [4x1 uint8]
                   ColorType: 'truecolor'
             DiffuseStrength: 0.6
            HandleVisibility: 'on'
                     HitTest: 'off'
                       Layer: 'back'
               NormalBinding: 'none'
                  NormalData: []
                      Parent: [1x1 Group]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: []
                     Texture: []
            TwoSidedLighting: 'off'
                  VertexData: [3x4 single]
               VertexIndices: []
                     Visible: 'on'
>> hLegend.BoxFace.ColorData  % 4x1 uint8
ans =
  128
  128
  128
  255   % this is the alpha value
</pre>
<p>As can be seen from this code snippet, the RGB ingredients (but not the alpha value) of <b>Color</b> have passed through to the <b>BoxFace</b>&#8216;s <b>ColorData</b>. The problem stems from <b>BoxFace</b>&#8216;s default <b>ColorType</b> value of <code>'truecolor'</code>. Once we set it to <code>'truecoloralpha'</code>, we can set <b>ColorData</b>&#8216;s alpha value to a value between <code>uint8(0)</code> and <code>uint8(255)</code>:</p>
<pre lang='matlab'>set(hLegend.BoxFace, 'ColorType','truecoloralpha', 'ColorData',uint8(255*[.5;.5;.5;.8]));  % [.5,.5,.5] is light gray; 0.8 means 20% transparent</pre>
<style type="text/css" media="screen">#content tr td { border: 0; padding: 0; text-align: center; background: white; }</style>
<table style="border:0;">
<tr>
<td><img loading="lazy" decoding="async" alt="Opaque (default) legend" src="https://undocumentedmatlab.com/images/TechChart_legend_100.gif" title="Opaque (default) legend" width="150" height="94" /></td>
<td><img loading="lazy" decoding="async" alt="20% transparent legend" src="https://undocumentedmatlab.com/images/TechChart_legend_80.gif" title="20% transparent legend" width="150" height="94" /></td>
<td><img loading="lazy" decoding="async" alt="50% transparent legend" src="https://undocumentedmatlab.com/images/TechChart_legend_50.gif" title="50% transparent legend" width="150" height="94" /></td>
</tr>
<tr>
<td>0% transparent (default)</td>
<td>20% transparent</td>
<td>50% transparent</td>
</tr>
<tr>
<td><b>ColorData</b> = <code>[128;128;128;<b>255</b>]</code></td>
<td><code>[128;128;128;<b>204</b>]</code></td>
<td><code>[128;128;128;<b>128</b>]</code></td>
</tr>
</table>
<p>Note 1: <b>ColorData</b> only accepts a column-vector of 4 uint8 values between 0-255. Attempting to set the value to a row vector or non-uint8 values will result in an error.<br />
Note 2: once we update the <b>BoxFace</b> color, the legend&#8217;s standard <b>Color</b> property loses its connection to the underlying <b>BoxFace.ColorData</b>, so updating <code>hLegend.Color</code> will no longer have any effect.<br />
<b>BoxFace.ColorType</b> also accepts <code>'colormapped'</code> and <code>'texturemapped'</code> values; the <b>BoxFace.ColorBinding</b> accepts values of <code>'none'</code>, <code>'discrete'</code> and <code>'interpolated'</code>, in addition to the default value of <code>'object'</code>. Readers are encouraged to play with these values for colorful effects (for example, gradient background colors).<br />
Finally, note that this entire discussion uses Matlab&#8217;s new graphics engine (HG2), on R2014b or newer. For those interested in semi-transparent legends in R2014a or older (HG1), this can be done as follows:</p>
<pre lang='matlab'>
% Prepare a fully-transparent legend (works in both HG1, HG2)
hLegend = legend(...);
set(hLegend, 'Color','none');  % =fully transparent
% This fails in HG2 since patch cannot be a child of a legend,
% but it works well in HG1 where legends are simple axes:
patch('Parent',hLegend, 'xdata',[0,0,1,1,0], 'ydata',[0,1,1,0,0], 'HitTest','off', 'FaceColor','y', 'FaceAlpha',0.2);  % 0.2 = 80% transparent
</pre>
<p>Note that making legends fully-transparent is easy in either HG1 or HG2: simply set the legend&#8217;s <b>Color</b> property to <code>'none'</code>. In HG2 this causes a quirk that the legend background becomes non-draggable (you can only drag the legend box-frame &#8211; transparent HG2 backgrounds to not trap mouse evens in the same way that opaque backgrounds do (i.e., when the HG2 legend has <b>Color</b>=<code>'w'</code>, the background is draggable just like the box-frame). In HG1, this does not happen, so a transparent background is just as draggable as an opaque one.<br />
In any case, as noted above, while making the legend fully-transparent is simple, making it semi-transparent is more problematic. Which is where this post could help.<br />
If you&#8217;ve found any other interesting use of these undocumented/hidden legend properties, please share it in a comment below. If you&#8217;d like me to develop a custom GUI (such as the charting program above or any other GUI) for you, please contact me by email or using my <a target="_blank" href="/contact">contact form</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparent-legend">Transparent legend</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/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
<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/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/persisting-transparent-colors-in-hg2" rel="bookmark" title="Persisting transparent colors in HG2">Persisting transparent colors in HG2 </a> <small>We can set semi- and fully-transparent colors in HG2 for multiple graphic objects, but making these settings stick is non-trivial. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/transparent-legend/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
