<?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>Malcolm Lidierth &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/malcolm-lidierth/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 19 Aug 2015 20:10:17 +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>Solving an mput (FTP) hang problem</title>
		<link>https://undocumentedmatlab.com/articles/solving-an-mput-ftp-hang-problem?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=solving-an-mput-ftp-hang-problem</link>
					<comments>https://undocumentedmatlab.com/articles/solving-an-mput-ftp-hang-problem#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 19 Aug 2015 20:10:17 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5974</guid>

					<description><![CDATA[<p>Matlab may hang when using passive FTP commands such as mput and dir.  A simple workaround is available to fix this. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/solving-an-mput-ftp-hang-problem">Solving an mput (FTP) hang problem</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/solving-a-matlab-hang-problem" rel="bookmark" title="Solving a Matlab hang problem">Solving a Matlab hang problem </a> <small>A very common Matlab hang is apparently due to an internal timing problem that can easily be solved. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-a-matlab-mcos-bug" rel="bookmark" title="Solving a Matlab MCOS bug">Solving a Matlab MCOS bug </a> <small>Matlab has a bug with handling multi-element class-access constructs. This post explains the problem and solution. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-a-matlab-bug-by-subclassing" rel="bookmark" title="Solving a MATLAB bug by subclassing">Solving a MATLAB bug by subclassing </a> <small>Matlab's Image Processing Toolbox's impoint function contains an annoying bug that can be fixed using some undocumented properties....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/java-class-access-pitfalls" rel="bookmark" title="Java class access pitfalls">Java class access pitfalls </a> <small>There are several potential pitfalls when accessing Matlab classes from Matlab. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab includes a variety of builtin utility functions that enable easy access to FTP. These functions are basically methods of an FTP object using Matlab&#8217;s old class system (for example, the <i><b>mput</b></i> function is implemented as <i>mput.m</i> in the <i>%matlabroot%\toolbox\matlab\iofun\@ftp\</i> folder). These are pretty old files that haven&#8217;t changed much in years.<br />
<span class="alignright"><img decoding="async" alt="FTP" src="https://undocumentedmatlab.com/images/FTP.gif" title="FTP" width="300" height="125" /></span>I recently needed to upload files from Matlab onto an FTP server, and discovered that calling <i><b>mput</b></i> simply hang Matlab to the point that I needed to kill and restart the Matlab process. The problem was not in the FTP server, since it could be accessed normally using FTP clients such as FileZilla and WinSCP. So it had to be something internal to Matlab. My initial workaround was to create an automation script (using WinSCP in my case) for the file upload. But this kludge is both non-robust as well as slow. A fix to the Matlab problem would be much better.<br />
Some online research yielded others who have complained about similar issues over the years, but I saw no concrete answer. I saw many references online to problems that relate to the combination of passive FTP with Windows 7 / firewall / Java 7, that suggested several fixes (<a target="_blank" rel="nofollow" href="https://technet.microsoft.com/en-us/library/dd421710(v=ws.10).aspx">example 1</a>, <a target="_blank" rel="nofollow" href="https://support.microsoft.com/en-us/kb/2754804">example 2</a>, <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/6990663/java-7-prevents-ftp-transfers-on-windows-vista-and-7-if-firewall-is-on-any-idea">example 3</a>, <a target="_blank" rel="nofollow" href="http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7077696">example 4</a>). However, none of them solved the problem: calling <i><b>mput</b></i> (or <i><b>dir</b></i> etc.) continued to freeze Matlab, forcing either a hard process kill or waiting several minutes for the timeout.<br />
Today, Malcolm Lidierth, author of the <a target="_blank" href="/articles/tag/waterloo">Waterloo graphics package</a>, told me that he also saw a similar situation on Mac. Fortunately, Malcolm discovered a much better solution to the problem than my external scripts workaround. It seems that simply setting the Java object underlying Matlab&#8217;s FTP object to use passive mode fixes the problem (possibly in addition to the other fixes mentioned above).<br />
<span id="more-5974"></span><br />
This can be done in two manners:<br />
The easiest is to add the following highlighted line in <i>mput.m</i>, on or about line 69 (the exact line may change based on your Matlab release):</p>
<pre lang='matlab' highlight='4'>
...
% Upload this file.
fis = java.io.FileInputStream(fileObject);
h.jobject.enterLocalPassiveMode();  % Use passive mode
status = h.jobject.storeFile(name,fis);
fis.close;
...
</pre>
<p>This works but has several limitations:</p>
<ol>
<li>it does not solve the problems of other passive FTP commands such as <i><b>dir</b></i>, although they can be solved in a similar manner</li>
<li>it creates a counter-problem when connecting to non-passive FTP servers &#8211; users might wish to make this a parameter of the <i><b>ftp</b></i> constructor function</li>
<li>and of course it requires changing Matlab&#8217;s installation files which is problematic in many aspects, as well as non-portable if you ever use your program on another machine or Matlab release.</li>
</ol>
<p>Here&#8217;s a much simpler, portable and flexible solution: simply set the underlying Java object&#8217;s passive mode after connecting to the server (using the <i><b>ftp</b></i> constructor function) but before using <i><b>mput</b></i> or <i><b>dir</b></i> or any other command that uses passive FTP mode:</p>
<pre lang='matlab' highlight='2'>
f = ftp('myftpserver.com',username,password);
cd(f);  sf=struct(f);  sf.jobject.enterLocalPassiveMode();
mput(f,filename);
dir(f);
close(f);
</pre>
<p>Note that we need to connect first, then get the underlying Java reference using the <a target="_blank" href="/articles/accessing-private-object-properties"><i><b>struct</b></i> hack</a> (since direct access to <code>f.jobject</code> is prevented), then we enter local passive mode, and only then we call <i><b>mput</b></i> to upload the file. If we omit the highlighted line in the script above, then <i><b>mput</b></i> (and <i><b>dir</b></i> etc.) will hang.<br />
This way, we can programmatically control when to use passive mode, and no changes to the Matlab install files is required: our Matlab script should now work on all platforms and Matlab releases.<br />
Note the seemingly unnecessary call to <i><b>cd</b>(f)</i> &#8211; this is done to ensure a valid connection before setting the passive mode. We should ensure to do this before each call to <i><b>mput</b></i>/<i><b>dir</b></i> etc., since otherwise, if the connection drops for any reason (e.g., timeout or some other disconnection), then the <i><b>mput</b></i>/<i><b>dir</b></i> command would reconnect without passive mode (causing a hang). By calling <i><b>cd</b>(f)</i> we ensure that the connection is done and passive mode is re-entered before <i><b>mput</b></i>/<i><b>dir</b></i> are called.<br />
As an interesting related note, <i><b>ftp</b></i> accepts an undocumented set of optional input parameters following its first 3 documented inputs (hostname, username and password). We can pass one or more of the following parameters in P-V (param name, param value) pairs format: System, LenientFutureDates, DefaultDateFormatStr, RecentDateFormatStr, ServerLanguageCode, ServerTimeZoneId, ShortMonthNames. All of these parameters expect string (<i><b>char</b></i>) values, except LenientFutureDates that expects a <i><b>logical</b></i> value (true/false). All the parameters have a default value of empty. An explanation of these parameters can be found in Apache&#8217;s documentation of the <a target="_blank" rel="nofollow" href="http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClientConfig.html"><code>FTPClientConfig</code></a> class (Matlab&#8217;s <i><b>ftp</b></i> uses a plain Apache <a target="_blank" rel="nofollow" href="http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html"><code>FTPClient</code></a> object, where you can also find an explanation of the <a target="_blank" rel="nofollow" href="http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#enterLocalPassiveMode()"><i>enterLocalPassiveMode</i></a> method that was used above).</p>
<h3 id="Italy">Italy visit, Aug 26 &#8211; Sep 1, 2015</h3>
<p>I will be traveling to north Italy between Aug 26 &#8211; Sep 1, 2015. If you happen to be in the area at that time, I will be happy to meet you to discuss how I could bring value to your work. Please email me (altmany at gmail) if you are interested.<br />
Due to my travel, this blog will take a short summer vacation, and will return in early September. Stay tuned!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/solving-an-mput-ftp-hang-problem">Solving an mput (FTP) hang problem</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/solving-a-matlab-hang-problem" rel="bookmark" title="Solving a Matlab hang problem">Solving a Matlab hang problem </a> <small>A very common Matlab hang is apparently due to an internal timing problem that can easily be solved. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-a-matlab-mcos-bug" rel="bookmark" title="Solving a Matlab MCOS bug">Solving a Matlab MCOS bug </a> <small>Matlab has a bug with handling multi-element class-access constructs. This post explains the problem and solution. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-a-matlab-bug-by-subclassing" rel="bookmark" title="Solving a MATLAB bug by subclassing">Solving a MATLAB bug by subclassing </a> <small>Matlab's Image Processing Toolbox's impoint function contains an annoying bug that can be fixed using some undocumented properties....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/java-class-access-pitfalls" rel="bookmark" title="Java class access pitfalls">Java class access pitfalls </a> <small>There are several potential pitfalls when accessing Matlab classes from Matlab. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/solving-an-mput-ftp-hang-problem/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Waterloo graphics animation and web deployment</title>
		<link>https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=waterloo-graphics-animation-web-deployment</link>
					<comments>https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 03 Jul 2013 18:00:38 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<category><![CDATA[Waterloo]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3944</guid>

					<description><![CDATA[<p>Waterloo graphics can be updated very quickly in Matlab, enabling plot animation; web deployment of the graphics is also possible. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment">Waterloo graphics animation and web deployment</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/waterloo-graphics-examples" rel="bookmark" title="Waterloo graphics examples">Waterloo graphics examples </a> <small>Some Matlab usage examples for the open-source Waterloo graphics package. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta" rel="bookmark" title="Waterloo graphics beta">Waterloo graphics beta </a> <small>The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I’d like to welcome guest blogger Malcolm Lidierth of King&#8217;s College London. Last week Malcolm wrote about <a target="_blank" href="/articles/waterloo-graphics-beta/">integrating the Waterloo graphing library in Matlab</a> figures. Today, Malcolm discusses advanced features in this library.<br />
Readers who are interested in high-quality plotting in Matlab may also be interested in the <a target="_blank" href="/articles/jfreechart-graphs-and-gauges/">JFreeChart</a> and <a target="_blank" rel="nofollow" href="https://code.google.com/p/mtex/">MTEX</a> open-source packages. JFreeChart provides chart types that are unavailable in Matlab, while MTEX builds upon existing Matlab plots using sophisticated data analysis and visualization. Unlike JFreeChart, I haven&#8217;t mentioned MTEX here before. MTEX is definitely worth a good mention, perhaps I&#8217;ll write about it someday. If you are using any other good charting packages for Matlab, please add a comment below.</i><br />
A feature request received from several of Yair&#8217;s readers for the Waterloo graphics project was for fast updating and animation of plots. This week, I&#8217;ll describe features supporting this. As those need to be illustrated here on a web page, I&#8217;ll also describe Waterloo&#8217;s new <i>deploy-to-web</i> feature.<br />
<center><figure style="width: 384px" class="wp-caption aligncenter"><img decoding="async" alt="Waterloo animated plot" src="https://undocumentedmatlab.com/images/Waterloo_animated3.gif" title="Waterloo animated plot" width="384" width="240" /><figcaption class="wp-caption-text">Waterloo animated plot</figcaption></figure></center><br />
<span id="more-3944"></span></p>
<h3 id="updating">Updating Waterloo plots</h3>
<p>Recall that Waterloo provides a Matlab OOP class called <code>GXPlot</code>, which wraps the underlying Waterloo plot type and can be retrieved using the <i>getObject()</i> method. For a <code>GXPlot</code> named <code>p</code>, the data can easily be updated from Matlab by passing it a new data array of values:</p>
<pre lang='matlab'>
p.getObject().getXData().setDataBufferData(XData);
p.getObject().getYData().setDataBufferData(YData);
</pre>
<p>This will be fast enough for most purposes, although the exchange of arrays between Matlab and Java is done by copying the data rather than by reference (a limitation imposed by the Java Native Interface rather than Matlab).<br />
If only a few data points are to be changed at any one time, an alternative approach is available of setting individual data points (referenced by their index, 0 being the first):</p>
<pre lang='matlab'>
p.getObject().getXData().setEntry(index, value);
p.getObject().getYData().setEntry(index, value);
</pre>
<p>These methods will update the plot <code>p</code>, as well as all other plots that <a target="_blank" href="/articles/waterloo-graphics-examples/#comment-132565">share its underlying data buffer</a>.<br />
All that is then needed is to update the display. This means:</p>
<ol>
<li>Optionally, checking and rescaling the axes as needed</li>
<li>Calling repaint on the graph or its container</li>
</ol>
<p>The best way will often be to make the container a listener on the relevant data object (the container houses the axes, so these will then be repainted if the scale changes). For example, for the YData:</p>
<pre lang='matlab'>
% get a reference to the plot's graph container
container = p.getObject().getParentGraph().getGraphContainer();
% attach the graph as a listener to the ydata buffer
dataObject = p.getObject().getYData();
dataObject.addPropertyChangeListener(p.getObject().getParentGraph());
</pre>
<p>Now any change to the YData object will fire a property change event causing the display to update.</p>
<h3 id="example">A simple example</h3>
<figure style="width: 352px" class="wp-caption alignright"><img decoding="async" alt="Waterloo animated bar plot" src="https://undocumentedmatlab.com/images/Waterloo_animated1.gif" title="Waterloo animated bar plot" width="352" width="220" /><figcaption class="wp-caption-text">Waterloo animated bar plot</figcaption></figure>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4], 'Name','TestUpdate1');
% Create some data and plot a bar chart
Y = hist(randn(1,100), 50);
container = gxgca();
p = bar(container, -1:0.0408:1, Y, 'BarWidth',0.0408, 'Fill','LIGHTCORAL');
container.getView().setAxesBounds(-1,0,2,225);
container.getView().setBackground(kcl.waterloo.defaults.Colors.getColor('WHEAT'));
container.getView().setBackgroundPainted(true);
refresh();
% Attach the graph as a listener to the ydata buffer
p.getObject().getYData().addPropertyChangeListener(p.getObject().getParentGraph());
% Now update the ydata in a loop - pausing for 0.1s on each iteration.
% The listener attached above will cause a repaint
for k = 1 : 50
    Y = hist(randn(1,100),50);
    Y = Y + p.getObject().getYData().getRawDataValues().';
    p.getObject().getYData().setDataBufferData(Y);
    pause(0.1);
end
</pre>
<p>Note that the repaints will be done on the <a target="_blank" href="/articles/matlab-and-the-event-dispatch-thread-edt/">Event Dispatch Thread (EDT)</a>. The call to the Matlab <i><b>pause</b></i> above causes EDT to be flushed so a full repaint is done for each iteration of the loop. Using a <i><b>timer</b></i>, as in the example below, can avoid this and allows the Swing repaint mechanisms to collapse multiple <i>repaint</i> calls into a single rendering operation. This will almost always be faster: use <i><b>drawnow</b></i> and <i><b>pause</b></i> sparingly with Waterloo code.</p>
<h3 id="speed">Improving speed</h3>
<p>Refreshing the display as above requires that</p>
<ol>
<li><i>the graph container is repainted together with the axes</i> &#8211; using internal axes that are rendered as part of step [2] will speed this up</li>
<li><i>the graph is repainted including grids and internal axes</i> &#8211; speed this up by turning off, or reducing the number of, grid lines. Switch off background painting – the container&#8217;s background will suffice (this is the default).</li>
<li><i>the plot displays are updated</i> &#8211; to speed this up:
<ul>
<li>Use objects that are easily translated into a square pixel-grid on screen. e.g. use squares instead of circles in a scatter plot</li>
<li>Use solid lines, not dashed or dotted ones</li>
<li>Turn off anti-aliasing of the plot</li>
</ul>
</li>
</ol>
<p>As painting is done on the EDT it will not block the Matlab thread. The time taken to update a plot will be variable, but it typically takes 5-20 msecs.</p>
<h3 id="updates">Fast plot updates</h3>
<p>In the beta release, new methods have been added to the plots: <i>plotRedraw()</i> and <i>plotUpdate()</i> both redraw a plot without refreshing the background, grids or axes.<br />
In the default implementation, <i>plotUpdate</i> simply calls <i>plotRedraw</i>: there actions are identical. <i>plotUpdate</i> is intended to be overridden in custom user subclasses to paint only points that have been added to end of a plot since the last update and the logic to do that needs to be added to the plot methods in those subclasses.<br />
This logic can also be synthesized on-the-fly (e.g. in Matlab, as in the example below) by adding NaNs in the data objects – Waterloo ignores these values. In the example below, a timer is used to update the plot.</p>
<pre lang='matlab'>
function update2(thisDelay)
    if nargin == 0
        DELAY = 0.01;
    else
        DELAY = thisDelay;
    end
    % Set up and create some data
    f = GXFigure();
    set(gcf, 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4], 'Name','TestAnimation');
    x = linspace(-pi*4, pi*4, 50);
    y = cos(x);
    % Now  the plot
    gr1 = subplot(f, 1,1, 1);
    p1 = line(gxgca, [], [], 'LineSpec', '-og');
    gr1.getObject().getView().setAxesBounds(-pi*4,-2.5,pi*8,5);
    % We'll draw 2 points only in each timer call below (2 points needed for interconnecting line)
    % This plot will therefore show only these points when the normal paint mechanism is
    % used unless all the data are added at the end: which the timer callback below does
    p1.getObject().setXData(x(1:2));
    p1.getObject().setYData(y(1:2)*2);
    p1.getObject().getParentGraph().setLeftAxisPainted(false);
    p1.getObject().getParentGraph().setRightAxisPainted(false);
    p1.getObject().getParentGraph().setTopAxisPainted(false);
    p1.getObject().getParentGraph().setBottomAxisPainted(false);
    p1.getObject().getParentGraph().setInnerAxisPainted(true);
    p1.getObject().getParentGraph().setInnerAxisLabelled(true);
    p1.getObject().getParentGraph().getGraphContainer().repaint();
    drawnow();
    t = timer('ExecutionMode','fixedSpacing', 'Period',DELAY, 'TimerFcn', {@localTimer, p1.getObject(), x, y});
    start(t);
    function localTimer(t, EventData, p1, x, y)
        k = get(t,'TasksExecuted');
        if k > numel(x)
            % Finished
            stop(t);
            p1.setXData(x);
            p1.setYData(y*2);
            p1.plotRedraw();
        elseif k > 1
            % Add 2 new data points to the plot
            p1.setXData(x(k-1:k));
            p1.setYData(y(k-1:k)*2);
            p1.plotRedraw();
        end
    end  % localTimer
end  % update2
</pre>
<p>Calls to <i>plotRedraw</i> and <i>plotUpdate</i> are extremely fast, typically 1-2 msecs. Each call to <i>plotRedraw()</i> adds two new data points to the existing plot. The result is the animated plot shown at the very top of this article.<br />
Notes:</p>
<ul>
<li>this example used the same timer callback to update both data and display; it will often be best to do this is separate callbacks – the refresh rates for data update and display animation can then be set independently.</li>
<li>readers who need plot animation may find interest in the related Matlab functions <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/comet.html"><i><b>comet</b></i></a> and <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/comet3.html"><i><b>comet3</b></i></a>, or this week&#8217;s POTW <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/pick/2013/06/28/multi-line-comet-plot/"><i><b>multicomet</b></i></a>.</li>
<li>plot animation in standard Matlab typically relies on the <b>EraseMode</b> property. In the upcoming HG2, this mechanism will no longer work, at least as seen in the <a target="_blank" href="/articles/hg2-update/">HG2 prequel</a> that is available today. So if your code uses any plot animation, you should expect it to break when HG2 is released (2014?), and you will need to convert your code to use HG2&#8217;s new animation functionality. Waterloo graphs and animation, being independent Java-based, are not expected to be affected, and will run the same way in both HG1 and HG2.</li>
</ul>
<h3 id="deployment">Deploying graphics to the web</h3>
<p>Waterloo enables export of static graphics to a variety of vector and bit-mapped formats (PNG, PDF, SVG etc.) that can be included in web pages. In the beta version, deployment to web is also supported directly, with automatic generation of the graphics files together with accompanying HTML files and optional CSS styling sheets and supporting Javascript. These are available from the Graph Editor, which is activated by double-clicking a graph and selecting the world (<img decoding="async" alt="Waterloo world icon" src="https://undocumentedmatlab.com/images/Waterloo_worldicon.png" title="Waterloo world icon" width="16" width="16" />) button.<br />
Two formats are presently supported:</p>
<ul>
<li>Scalable Vector Graphics (SVG). By default, the generated files provide conversion of the SVG to HTML5 canvas commands when loaded into a browser via the <a target="_blank" rel="nofollow" href="http://code.google.com/p/canvg/"><i>canvg.js</i></a> JavaScript by Gabe Lerner. Use of <i>canvg</i> provides better cross-browser consistency in the rendering of the graphics, particularly for text. Note that only static graphics are presently supported with SVG.</li>
<li>Through the <a target="_blank" rel="nofollow" href="http://www.processing.org">Processing</a> script language for visual arts and <a target="_blank" rel="nofollow" href="http://www.processingjs.org"><i>processing.js</i></a> JavaScript.</li>
</ul>
<p>Processing script output supports animations using a new class developed for Waterloo (<a target="_blank" rel="nofollow" href="http://waterloo.sourceforge.net/PDEGraphics2D/"><code>PDEGraphics2D</code></a>), which also supports an AWT/Swing container. The generated script files can be loaded and customized using the <i>Process.app</i> file available at the web site above.<br />
In addition, experimental (and presently quirky) support for generating animated GIFs is included. The animations for this blog were generated using this. Animated GIFs are to be preferred when vector graphics are not required because GIFs</p>
<ul>
<li>are universally and consistently supported in browsers</li>
<li>are smaller and less computationally intensive. They therefore consume less power and are environmentally friendlier. Visitors to a website, especially those using battery-powered devices, are likely to stay longer on the site.</li>
</ul>
<p>For the present, only static graphics are supported through the GUIs, so animations need to be created programmatically. A &#8220;record&#8221; button will be added to the GUIs in future Waterloo releases.<br />
Users can edit the default settings for deployment using the preferences editor, now available from the Graph Editor using the key (<img decoding="async" alt="Waterloo key icon" src="https://undocumentedmatlab.com/images/Waterloo_keyicon.png" title="Waterloo key icon" width="16" width="16" />) button. For SVG, the options are shown below: allowing a choice of whether SVG is to be embedded in the generated HTML file; whether canvg.js should be used and selection of a styling sheet. Customize the file addresses relative to the target folder for the HTML file or use a URL. The &#8220;httpd.py&#8221; file here is a Python 2.7 script that will set up a local server and display the HTML file in your system browser – it is needed only if the security rules for your browser prevent the files being loaded directly from the local file system.<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Waterloo preferences window" src="https://undocumentedmatlab.com/images/Waterloo_preferences.png" title="Waterloo preferences window" width="400" height="256" /><figcaption class="wp-caption-text">Waterloo preferences window</figcaption></figure></center><br />
By default, the deploy tool uses a template <i>index.html</i> file that is embedded in the distribution. You can specify your own instead, although I have not yet added that to the Preferences GUI.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment">Waterloo graphics animation and web deployment</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/waterloo-graphics-examples" rel="bookmark" title="Waterloo graphics examples">Waterloo graphics examples </a> <small>Some Matlab usage examples for the open-source Waterloo graphics package. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta" rel="bookmark" title="Waterloo graphics beta">Waterloo graphics beta </a> <small>The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment/feed</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Waterloo graphics beta</title>
		<link>https://undocumentedmatlab.com/articles/waterloo-graphics-beta?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=waterloo-graphics-beta</link>
					<comments>https://undocumentedmatlab.com/articles/waterloo-graphics-beta#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 26 Jun 2013 18:00:20 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<category><![CDATA[Waterloo]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3907</guid>

					<description><![CDATA[<p>The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta">Waterloo graphics beta</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/waterloo-graphics-examples" rel="bookmark" title="Waterloo graphics examples">Waterloo graphics examples </a> <small>Some Matlab usage examples for the open-source Waterloo graphics package. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment" rel="bookmark" title="Waterloo graphics animation and web deployment">Waterloo graphics animation and web deployment </a> <small>Waterloo graphics can be updated very quickly in Matlab, enabling plot animation; web deployment of the graphics is also possible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I&#8217;d like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King’s College London. Malcolm has written several articles here, including a <a target="_blank" href="/articles/waterloo-graphics/">couple of articles</a> on his Waterloo graphing library. Today, Malcolm discusses new features in this library, as it matures into an official beta phase.</i><br />
<center><figure style="width: 295px" class="wp-caption alignright"><img decoding="async" alt="Waterloo contour plot of Matlab's penny image" src="https://undocumentedmatlab.com/images/lincoln.jpg" title="Waterloo contour plot of Matlab's penny image" width="295" height="284" /><figcaption class="wp-caption-text">Waterloo contour plot of Matlab's penny image</figcaption></figure></center> Last year, Yair kindly allowed me space for a couple of guest blogs on the <a target="_blank" rel="nofollow" href="http://sourceforge.net/projects/waterloo/">Waterloo graphics</a> open-source project. Waterloo has recently transitioned to a &#8216;beta&#8217; release status, with several new features – many of them in response to suggestions from readers of this blog. Many thanks to all who made those.<br />
One of the motivations in writing Waterloo was to get better, less pixellated graphs in Matlab. By using Java 2D, the core library is not tied to Matlab. Waterloo graphics can be used wherever there is access to a Java Virtual Machine: R, ScilLab etc. MathWorks obviously feel the need for better graphics too: Yair recently blogged about the <a target="_blank" href="/articles/hg2-update/">next generation Matlab graphics (HG2)</a>. The Waterloo beta release provides support for mixing both Waterloo graphs and Matlab HG2 graphs in a single figure (as well as current HG1 graphics of course).<br />
The new features in the Waterloo beta can be summarized as:</p>
<ol>
<li>Introducing new plot types: contours, bars, polar and area charts</li>
<li>Mouse-selectable regions of interest</li>
<li>Support for fast-plot updates without redrawing the entire graph</li>
<li>Support for web-deployment of the graphs using <a target="_blank" rel="nofollow" href="http://www.w3.org/Graphics/SVG/">SVG</a> or <a target="_blank" rel="nofollow" href="http://www.processing.org">Processing</a> and <a target="_blank" rel="nofollow" href="http://processingjs.org">ProcessingJS</a></li>
</ol>
<p>Today I will concentrate on [1] and [2], illustrated with some Matlab examples; I will discuss [3] and [4] next week.<br />
<span id="more-3907"></span></p>
<h3 id="installation">Installation of Waterloo in Matlab</h3>
<p>For those readers who have not yet installed Waterloo in Matlab, the process is very simple: download the <a target="_blank" rel="nofollow" href="http://sourceforge.net/projects/waterloo/files/latest/download">latest zip file</a> and extract it. All the sub-folders in the <i>waterloo</i> folder are needed but only the <i>Waterloo_MATLAB_Library</i> subfolder (not its subfolders) should be added to the Matlab path. Once installed, just type <i><b>waterloo</b></i> at the Matlab prompt in each Matlab session.<br />
A Matlab script file that will do it all is available here (<a target="_blank" href="/files/Waterloo_installer.m">Waterloo_installer.m</a>). The script is harmless to run if you already have Waterloo installed, but if not then it will automatically find the latest zip file on SourceForge, download and install it, and then configure the Matlab path appropriately.</p>
<h3 id="contour">Contour plots</h3>
<p>I ended my <a target="_blank" href="/articles/waterloo-graphics-examples/">last guest article</a> with an example of work-in-progress: filled contours. The beta release now fully supports these.<br />
Recall from the <a target="_blank" href="/articles/waterloo-graphics/">previous articles</a> that <code>GXFigure</code> creates a Waterloo-compatible Matlab figure window. <i>gxgca()</i> returns a reference to the container for the graph as a Matlab <code>GXGraph</code> object, much as Matlab&#8217;s built-in <i><b>gca</b></i> returns an axes reference.<br />
Here is Matlab&#8217;s Lincoln penny demo in Waterloo:</p>
<pre lang='matlab'>
% Get some pre-defined colors
colors = [kcl.waterloo.defaults.Colors.getColor(0)];
for k = 1 : 17
    colors = horzcat(colors,kcl.waterloo.defaults.Colors.getColor(k));
end
f = GXFigure();
set(gcf, 'Name','Filled Contour', 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4])
load penny;
ax = subplot(f,1,1,1);
ax.getObject().setAspectRatio(1);
p2 = contourf(ax, flipud(P), 18, 'LineStyle','-', 'LineWidth',0.4);
p2.getObject().setFillClipping(false);
p2.getObject().setFill(colors);
drawnow();
</pre>
<p>(resulting in the contour plot above)<br />
To transform Abe Lincoln to a logarithmic world, just double-click the graph and select the log transform. The result is shown on the right here:<br />
<center><figure style="width: 200px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Transformed Matlab penny image" src="https://undocumentedmatlab.com/images/lincoln_contour.jpg" title="Transformed Matlab penny image" width="200" height="195" /><figcaption class="wp-caption-text">Transformed Matlab penny image</figcaption></figure></center> All plots in Waterloo share a common data model, including contour plots. For a scatter plot, <code>x, y</code> pairs in a set represent the offsets to display a marker e.g. a circle or square that is generally of fixed size. For a contour plot, the marker is the contour line and the values for that incorporate the offsets. The <code>xdata</code> and <code>ydata</code> are added during plotting; while these will normally be zero, this makes it trivial to construct montages of contour plots simply by using non-zero values.<br />
Plainly, this needs some extra work to support the common model: circles for a scatter plot are still painted as fixed diameter circles when the plot is rescaled or transformed but the pixel values for a contour line, bar plot etc will need to be recalculated. To achieve this:</p>
<ul>
<li>the data model incorporates an extra object to do the work</li>
<li>such plots implement a new interface – <code>GJTransformUpdateInterface</code> – that specifies a <i>transformUpdate()</i> method that refreshes the pixel-coordinates. End-users will not normally need to concern themselves with this, as <i>transformUpdate</i> method will be called by the listeners as required.</li>
</ul>
<h3 id="categorical">Categorical data</h3>
<p>Waterloo always uses numeric data to position markers, bars etc in a plot. However, categorical data can be used to supplement those data. Here is an example using the new bar plot:<br />
<center><figure style="width: 320px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Categorized Waterloo bar plot" src="https://undocumentedmatlab.com/images/categorised_bar.png" title="Categorized Waterloo bar plot" width="316" height="183" /> <img loading="lazy" decoding="async" alt="Categorized Waterloo bar plot" src="https://undocumentedmatlab.com/images/categorised_labelled.png" title="Categorized Waterloo bar plot" width="318" height="191" /><figcaption class="wp-caption-text">Categorized Waterloo bar plots</figcaption></figure></center></p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Name','TestBar4', 'Units','normalized', 'Position',[0.1 0.1 0.8 0.8]);
m = {'Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'};
gr1 = subplot(f, 2, 2, 1);
a = bar(gr1, 1:12, 1:12);
for k = 1 : 12
   a.getObject().getDataModel().getXData().setCategory(k, m{k});
end
gr1.getObject().setTitleText('Label using the XData categories');
gr1.getObject().getView().autoScale();
</pre>
<p>Support for categorical labels on the axes is supported for all plots via the common data model. For bar charts, the extra object associated with the plot also supports adding labels to the bars themselves:</p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Name','Categorized Bars', 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4]);
m = {'Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'};
gr = subplot(f, 1, 1, 1);
c = barh(gr, 1:10, 1:10,'stacked');
c.getObject().setFill([java.awt.Color.yellow, java.awt.Color.blue]);
c.getObject().getDataModel().getExtraObject().setFontForeground([java.awt.Color.BLACK, java.awt.Color.WHITE]);
for k = 1 : 12
   c.getObject().getDataModel().getExtraObject().getLabels().add(k-1, m{k});
end
gr.getObject().getView().autoScale();
</pre>
<p>Note that the standard method <i>setFill</i>, is used to set the bar colors and as two colors are supplied the data are assumed to contain a pair of multiplexed series. This is common to all plots.<br />
To customize the labels, we need to set a property in the extra object which is retrieved with a call to <i>c.getObject().getDataModel().getExtraObject()</i>.<br />
The same principles apply to pie charts:<br />
<center><figure style="width: 200px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Labelled Waterloo pie chart" src="https://undocumentedmatlab.com/images/pie.png" title="Labelled Waterloo pie chart" width="200" height="204" /><figcaption class="wp-caption-text">Labelled Waterloo pie chart</figcaption></figure></center></p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Name','TestPie1', 'Units','normalized', 'Position',[0.1 0.1 0.8 0.8]);
colors = [kcl.waterloo.defaults.Colors.getColor(0)];
y = ones(1,18)*100/18;
gr = subplot(f, 1, 1, 1);
colors = [kcl.waterloo.defaults.Colors.getColor(1),...
    kcl.waterloo.defaults.Colors.getColor(17),...
    kcl.waterloo.defaults.Colors.getColor(2),...
    kcl.waterloo.defaults.Colors.getColor(16),...
    kcl.waterloo.defaults.Colors.getColor(3),...
    kcl.waterloo.defaults.Colors.getColor(15),...
    kcl.waterloo.defaults.Colors.getColor(4),...
    kcl.waterloo.defaults.Colors.getColor(14)];
c = pie(gr, [10 20 45 42 22 26 42 20], logical([0 0 1]), 'FaceColor',colors);
</pre>
<h3 id="polar">Polar charts</h3>
<p>Polar bar and compass charts are also now supported:<br />
<center><figure style="width: 500px" class="wp-caption alignright"><a target="_blank" href="/images/polar_bar2.gif"><img loading="lazy" decoding="async" alt="Waterloo polar bar chart (click for details)" src="https://undocumentedmatlab.com/images/polar_bar2.gif" title="Waterloo polar bar chart (click for details)" width="241" height="230" /></a><a target="_blank" href="/images/compass.png"><img loading="lazy" decoding="async" alt="Waterloo compass chart (click for details)" src="https://undocumentedmatlab.com/images/compass.png" title="Waterloo compass chart (click for details)" width="248" height="230" /></a><figcaption class="wp-caption-text">Waterloo polar bar and compass charts (click for details)</figcaption></figure></center></p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Name','TestPie1', 'Units','normalized', 'Position',[0.1 0.1 0.8 0.8]);
load sunspot.dat  % Contains a 2-column vector named sunspot
colors = [kcl.waterloo.defaults.Colors.getColor(0)];
for k = 1 : 17
    colors = horzcat(colors,kcl.waterloo.defaults.Colors.getColor(k));
end
gr1 = subplot(f, 1,2, 1);
a = polarbar(gr1, sunspot(1:48,2), 'FaceColor',colors, 'EdgeWidth',0.5);
[a,b] = hist(sunspot(:,2),12);
gr2 = subplot(f, 1,2, 2);
b = polarbar(gr2, a, 'FaceColor',colors);
Z = eig(randn(20,20));
a = compass(gr1, real(Z), imag(Z), 'LineColor','r');
</pre>
<h3 id="area">Area plots</h3>
<p>Area plots are supported through a new plot class and also by having all plots implement a new Java interface. To illustrate, create two line plots:<br />
<center><figure style="width: 300px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Waterloo area-fill chart" src="https://undocumentedmatlab.com/images/areaFill1.png" title="Waterloo area-fill chart" width="300" height="141" /><figcaption class="wp-caption-text">Waterloo area-fill chart</figcaption></figure></center></p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Name','TestAreaFill', 'Units','normalized', 'Position',[0.4 0.1 0.5 0.4]);
x = 0.5 : 0.5 : 10;
y = sin(x);
gr1 = gxgca();
a1 = line(gr1, x, y, 'LineSpec','-ob');
b1 = line(gr1, x, y*2, 'LineSpec','-sg');
gr1.getObject().getView().autoScale();
% Filling the area between the two plots requires one extra line and a refresh call to paint the result:
a1.getObject().setAreaFill(b1.getObject());
refresh();
</pre>
<p>All the work is done in the Java code because plots now implement the <code>GJFillable</code> interface. All that is required is to call the <i>setAreaFill()</i> method on a class implementing <code>GJFillable</code>, specifying another <code>GJFillable</code> as input.<br />
A new java class, <code>GJFill</code>, also implements <code>GJFillable</code> and can be used to fill an area relative to a scalar constant or an arbitrary shape. I have also written a Matlab wrapper class for this (<code>GXFill</code>, see below) but I shall use a Java-based example here.<br />
Whether the fill is made horizontally (from the plot) or vertically (from the axes) can be selected by setting the orientation property of the <code>GJFill</code> instance. This can also be set to arbitrary, in which case we can create a custom fillable area sythesized from <code>java.geom</code> shapes:<br />
<center><figure style="width: 300px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Waterloo full area fill chart" src="https://undocumentedmatlab.com/images/areaFill2.png" title="Waterloo full area fill chart" width="300" height="177" /> <img loading="lazy" decoding="async" alt="Waterloo custom area fill chart" src="https://undocumentedmatlab.com/images/areaFill3b.png" title="Waterloo custom area fill chart" width="300" height="177" /><figcaption class="wp-caption-text">Waterloo full (above) &amp; custom (below) area fill charts</figcaption></figure></center></p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Name','Constant Fill', 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4]);
x = 0.5 : 0.5 : 10;
y = sin(x);
gr1 = subplot(f, 1, 1, 1);
a1 = line(gxgca, x+1, y+3, 'LineSpec','-sg');
% Now create a GJFill instance, using a constant as the reference (1.5 in this case), and use this as this area's fill
v = kcl.waterloo.graphics.plots2D.GJFill(a1.getObject(), 1.5);
a1.getObject().setAreaFill(v);
%% Start complex
   % Alternately, we can use an arbitrary fill shape:
   v.setOrientation(javaMethod('valueOf', 'kcl.waterloo.graphics.plots2D.GJFill$ORIENTATION', 'ARBITRARY'));
   a1.getObject().setAreaFill(v);
   % Create a shape (which can be complex)
   area = java.awt.geom.Area(javaObject('java.awt.geom.Rectangle2D$Double',1,1,5,5));
   area.add(java.awt.geom.Area(javaObject('java.awt.geom.Rectangle2D$Double',8,1,2,5)));
   % Add the shape to the GJFill instance
   v.setArbitraryArea(java.awt.geom.Area(area));
%% End complex
% Customize the fill color
v.setAreaPaint(java.awt.Color(0,1,0,0.5));
% Manually rescale and refresh the plot
gr1.getObject().getView().setAxesBounds(0,0,12,5);
refresh();
</pre>
<p>To make this simpler from Matlab, a new Matlab class <code>GXFill</code> is provided. This constructs and adds a fill in a single step:</p>
<pre lang='matlab'>fill = GXFill(plot_reference, value, orientation);</pre>
<p>where <code>value</code> is a scalar or a Java <code>Shape</code> object, and <code>orientation</code> is a string e.g. &#8216;horizontal&#8217;. Note that the coordinates are specified in axes units and they will rescale and be transformed as needed when the axes are changed.</p>
<h3 id="ROI">Specifying/selecting ROIs</h3>
<p>Finally, regions of interest (ROIs) can be selected both programmatically and with the mouse. One of these can be set as the &#8220;current&#8221; ROI and that is the one that is mouse selectable: set the current ROI using shift-left mouse drag, set the region and rescale to display only that region using shift-right mouse drag.<br />
To create an ROI that can be dragged and resized, add a <code>GJRoi</code> instance to the graph, e.g. with an existing current ROI selected:</p>
<pre lang='matlab'>
gr = gxgca;
gr = gr.getObject().getView();
gr.add(kcl.waterloo.graphics.GJRoi.createInstance(gr, gr.getCurrentROI()));
</pre>
<h3 id="java">Waterloo and Matlab&#8217;s Java support</h3>
<p>Note: It appears that HG2, like HG1, creates an offscreen bitmap that is then blitted onto a Java <code>Canvas</code> within a Matlab figure. Matlab <a target="_blank" rel="nofollow" href="https://www.mathworks.com/support/contact_us/dev/javaframe.html">warns</a> that the JavaFrame property will (no longer may) be discontinued in some future release, but it is my guess that this will not be the case when HG2 is released. A new set of uicontrols may indeed be included using a C-based library like <a target="_blank" rel="nofollow" href="http://www.wxwidgets.org">wxWidgets</a> or <a target="_blank" rel="nofollow" href="https://qt-project.org">Qt</a>. However, it seems unlikely that Java support will be dropped completely – too much of Matlab&#8217;s GUI uses Java (for example, the new desktop introduced in R2012b is entirely Java-based). So the Waterloo Matlab library should work, even if a switch is needed to using <code>JFrame</code>s instead of Matlab figures for output.<br />
For the adventurous, Waterloo graphs can also be deployed using <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/JavaFX">JavaFX</a> via the <a target="_blank" rel="nofollow" href="http://download.java.net/jdk8/jfxdocs/javafx/embed/swing/SwingNode.html">SwingNode</a> class – but that requires installation of the latest <a target="_blank" rel="nofollow" href="https://jdk8.java.net/download.html">Java 8</a> (currently in early release status). Noting that Matlab is still (as of R2013a) using Java 6, this may indeed be a big jump (note last week&#8217;s article on <a target="_blank" href="/articles/using-java-7-in-matlab-r2013a-and-earlier/">upgrading Matlab to use Java 7</a>).<br />
Naturally, Waterloo&#8217;s graphs and classes can also be used in stand-alone Java applications, entirely outside Matlab, even on a $30 ARM6 <a target="_blank" rel="nofollow" href="http://www.raspberrypi.org">Raspberry Pi</a>.<br />
Next week, I will look at methods for animating plots (e.g. using Matlab timers) and deploying vector graphics to web pages using the in-built GUIs.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta">Waterloo graphics beta</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/waterloo-graphics-examples" rel="bookmark" title="Waterloo graphics examples">Waterloo graphics examples </a> <small>Some Matlab usage examples for the open-source Waterloo graphics package. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment" rel="bookmark" title="Waterloo graphics animation and web deployment">Waterloo graphics animation and web deployment </a> <small>Waterloo graphics can be updated very quickly in Matlab, enabling plot animation; web deployment of the graphics is also possible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/waterloo-graphics-beta/feed</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>Waterloo graphics examples</title>
		<link>https://undocumentedmatlab.com/articles/waterloo-graphics-examples?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=waterloo-graphics-examples</link>
					<comments>https://undocumentedmatlab.com/articles/waterloo-graphics-examples#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 05 Dec 2012 18:00:50 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<category><![CDATA[Waterloo]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3374</guid>

					<description><![CDATA[<p>Some Matlab usage examples for the open-source Waterloo graphics package. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics-examples">Waterloo graphics examples</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/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta" rel="bookmark" title="Waterloo graphics beta">Waterloo graphics beta </a> <small>The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment" rel="bookmark" title="Waterloo graphics animation and web deployment">Waterloo graphics animation and web deployment </a> <small>Waterloo graphics can be updated very quickly in Matlab, enabling plot animation; web deployment of the graphics is also possible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity" rel="bookmark" title="Improving graphics interactivity">Improving graphics interactivity </a> <small>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Last week, guest blogger <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> wrote about the open-source <a target="_blank" href="/articles/waterloo-graphics/">Waterloo graphics</a> package and how it can be used in Matlab. Today, Malcolm continues the discussion of Waterloo with a set of examples in Matlab code.<br />
Note: I highly recommend checking out Malcolm&#8217;s other open-source submissions/utilities on the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/index?term=authorid%3A23816">Matlab File Exchange</a>.</i><br />
<br /> &nbsp; <br />
The Waterloo graphics routines provide three potential APIs for MATLAB-users:</p>
<ul>
<li>A Java API for the core code provides a simple and consistent mechanism for creating plots using the same data model for each of them, from line and scatter through quiver and contour plots.</li>
<li>A Groovy API that can be used to call the Java API via some static methods that use Groovy&#8217;s dynamic typing mechanisms and so allows the same code to be called with different classes on input from different environments – a cell array from MATLAB for example.</li>
<li>A Matlab API that mimics the standard MATLAB graphics routines and variously calls the Java-API and Groovy API as required.</li>
</ul>
<p>I will concentrate here on the Matlab API, which is likely to be of more interest to the majority of readers. This uses Matlab OOP wrappers for the underlying Java objects and all provide access to them by using the <i>getObject()</i> method on the wrappers, so Matlab and Java code can be easily mixed.</p>
<h3 id="simple">Simple Waterloo plots</h3>
<p>To create a Matlab figure that can accept Waterloo graphics call <i><b>GXFigure</b></i> instead of <i><b>figure</b></i> e.g.</p>
<pre lang='matlab'>f = GXFigure(10);</pre>
<p>creates figure 10 and enables it for Waterloo.<br />
In Matlab, you might use <i><b>gca</b></i> to create a figure and a set of axes – for Waterloo use <i><b>gxgca</b></i> instead. The graph reference also needs to be provided as input to force Matlab to use the Waterloo plotting methods. So</p>
<pre lang='matlab'> scatter(1:10,1:10,'^r')</pre>
<p>in Matlab becomes:</p>
<pre lang='matlab'>scatter(gxgca, 1:10,1:10,'^r')</pre>
<p>Here are the outputs:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Simple Matlab plot" src="https://undocumentedmatlab.com/images/Waterloo_ex1a_450x378.jpg" title="Simple Matlab plot" width="450" height="378" /> <br />
<img loading="lazy" decoding="async" alt="Simple Waterloo plot" src="https://undocumentedmatlab.com/images/Waterloo_ex1b_450x378.jpg" title="Simple Waterloo plot" width="450" height="378" /><figcaption class="wp-caption-text">Simple Matlab and Waterloo plots</figcaption></figure></center><br />
<span id="more-3374"></span><br />
Note that <i><b>gxgca</b></i> returns <i><b>gca</b></i> if the current axes are not Waterloo-enabled (so its use above would have produced a Matlab scatter plot in that case). If there is no current axes object, it creates a Waterloo <code>GXGraph</code> and returns a reference to it (just as <i><b>gca</b></i> creates Matlab axes when there are none).<br />
However, Waterloo does not attempt to completely mimic Matlab: the markers above were specified as &#8216;^r&#8217;. A full LineSpec (e.g., &#8216;-^r&#8217;) would produce an error when given to the scatter function in Matlab, but Waterloo does not care – if a property is specified that is inappropriate it will be ignored. That is because the Matlab properties are translated into a set of Java properties that all plots have in common, but not all plots use. Note also, that <i><b>hold</b></i> is effectively &#8216;on&#8217; for Waterloo, markers are filled and grids are drawn by default (but all the defaults are user-editable).</p>
<h3 id="combining">Combining Waterloo plots</h3>
<p>Waterloo plots can be added together. To draw a line through a set of scatter points, a line plot is added to it. Similarly, an error bar plot can be added to that. The Waterloo Matlab-API has an <i><b>errorbar</b></i> function that does that. As the plots are additive the process can be continued to create a series of such compound plots:</p>
<pre lang='matlab'>
f = GXFigure();
ax = subplot(f,1,1,1);
set(gcf, 'Units', 'normalized', 'Position', [0.1 0.1 0.8 0.8], 'Name', 'TestError');
x = 0.5 : 0.5 : 10;
y = log(x);
a1 = errorbar(ax, x, y, y/3.5, 'LineSpec', '-ob');
errorbar(a1, [], y*2, y/3.5*2,'LineSpec', '-sg');
errorbar(a1, [], y*5, y/3.5*5, 'LineSpec', '-dr');
Y = errorbar(a1, [], y*10, y/3.5*10, 'LineSpec', '-^m');
ax.getObject().getView().autoScale();
</pre>
<p>Here I have created a GXFigure, used its subplot method to create a graph, plotted the first errorbar series to it and parented the remaining plots from the first. As they share their x-data, that is specified as empty for the last three plots.<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Combining Waterloo plots" src="https://undocumentedmatlab.com/images/Waterloo_ex2_450x378.jpg" title="Combining Waterloo plots" width="450" height="378" /><figcaption class="wp-caption-text">Combining Waterloo plots</figcaption></figure></center><br />
The final line above looks less Matlab-like. For</p>
<pre lang='matlab'>ax.getObject().getView().autoScale();</pre>
<ul>
<li><code>ax</code> is the Matlab OOP wrapper created by subplot – it&#8217;s a <code>GXGraph</code>.</li>
<li><i>ax.getObject()</i> returns the Java Swing container which has a &#8220;view&#8221; (which is the graph)</li>
<li><i>ax.getObject().getView()</i> returns the graph</li>
</ul>
<p><i>ax.getObject().getView().autoScale()</i> just causes the graph to be auto-scaled to fit in all the graphics. The axes can be moved, expanded and shrunk using the mouse and double-clicking displays a GUI editor as shown last week. Clicking on a plot causes the plot to become the current Waterloo graphic object, which can then be accessed with <i><b>gxgco</b></i> instead of <i><b>gco</b></i> (just as <i><b>gxgca</b></i> was used in place of <i><b>gca</b></i>).</p>
<h3 id="subplots">Combining Matlab and Waterloo sub-plots</h3>
<p>I have shown only single-axes plots till now. The <i><b>subplot</b></i> function can, as in Matlab, create multiple axes and these can be used to mix Waterloo and Matlab graphics in a single figure as here (upper-left and lower-right are Matlab):<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Mixing Matlab and Waterloo subplots" src="https://undocumentedmatlab.com/images/Waterloo_ex7_450x311.jpg" title="Mixing Matlab and Waterloo subplots" width="450" height="311" /><figcaption class="wp-caption-text">Mixing Matlab and Waterloo subplots</figcaption></figure></center></p>
<h3 id="extra">Some additional examples</h3>
<p>Here then are a few more plot examples:</p>
<pre lang='matlab'>
f = GXFigure();
set(f.Parent, 'Units', 'normalized', 'Position', [.2 .2 .6 .6], 'Name', 'TestQuiver');
[X,Y] = meshgrid(-2:.2:2);
Z = X.*exp(-X.^2 - Y.^2);
[DX,DY] = gradient(Z,.2,.2);
ax = subplot(gxgcf,1,1,1);
q1 = quiver(ax,X,Y,DX,DY, 0.9);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Waterloo quiver plot" src="https://undocumentedmatlab.com/images/Waterloo_ex3_450x400.jpg" title="Waterloo quiver plot" width="450" height="400" /><figcaption class="wp-caption-text">Waterloo quiver plot</figcaption></figure></center></p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Units', 'normalized', 'Position', [0.1 0.1 0.8 0.8], 'Name', 'TestStairs');
x = linspace(-2*pi,2*pi,40);
y = sin(x);
ax = subplot(f, 1, 2, 1);
a1 = stairs(gxgca, x, y, 'LineColor', 'r');
b1 = stairs(gxgca, x, y*2,'LineColor', 'g');
c1 = stairs(gxgca, x, y*5,'LineColor', 'm');
d1 = stairs(gxgca, x, y*10,'LineColor', 'b');
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Waterloo stairs plot" src="https://undocumentedmatlab.com/images/Waterloo_ex4_450x303.jpg" title="Waterloo stairs plot" width="450" height="303" /><figcaption class="wp-caption-text">Waterloo stairs plot</figcaption></figure></center></p>
<pre lang='matlab'>
load penny;
f = GXFigure();
ax = subplot(f,1,1,1);
ax.getObject().setAspectRatio(1);  % This sets the aspect ratio of the view in the container
p2 = contour(ax, flipud(P), 30);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Waterloo contour plot" src="https://undocumentedmatlab.com/images/Waterloo_ex5_450x368.jpg" title="Waterloo contour plot" width="450" height="368" /><figcaption class="wp-caption-text">Waterloo contour plot</figcaption></figure></center><br />
I have added labels and titles here using the GUI editor – they can of course also be set programmatically.</p>
<h3 id="future">Future work</h3>
<p>Waterloo is far from finished and more plot types are being added. Here is a taster of a filled contour plot which will be available in the next update (see the <a target="_blank" rel="nofollow" href="http://sourceforge.net/p/waterloo/code/">development version GIT repository</a>):</p>
<pre lang='matlab'>
f = GXFigure();
set(gcf, 'Name', 'TestContour', 'Units', 'normalized', 'Position', [0.2 0.2 0.7 0.5])
ax = subplot(f,1,1,1);
ax.getObject().setAspectRatio(1);
p1 = contourf(ax, peaks(100), 20);
p1.getObject().setAlpha(0.3);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Waterloo filled contour plot" src="https://undocumentedmatlab.com/images/Waterloo_ex6_450x392.jpg" title="Waterloo filled contour plot" width="450" height="378" /><figcaption class="wp-caption-text">Waterloo filled contour plot</figcaption></figure></center><br />
If you have any comments or feedback on Waterloo, please feel free to join its open-source development effort, or simply leave a <a href="/articles/waterloo-graphics-examples#respond">comment below</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics-examples">Waterloo graphics examples</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/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta" rel="bookmark" title="Waterloo graphics beta">Waterloo graphics beta </a> <small>The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment" rel="bookmark" title="Waterloo graphics animation and web deployment">Waterloo graphics animation and web deployment </a> <small>Waterloo graphics can be updated very quickly in Matlab, enabling plot animation; web deployment of the graphics is also possible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity" rel="bookmark" title="Improving graphics interactivity">Improving graphics interactivity </a> <small>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/waterloo-graphics-examples/feed</wfw:commentRss>
			<slash:comments>48</slash:comments>
		
		
			</item>
		<item>
		<title>Waterloo graphics</title>
		<link>https://undocumentedmatlab.com/articles/waterloo-graphics?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=waterloo-graphics</link>
					<comments>https://undocumentedmatlab.com/articles/waterloo-graphics#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 28 Nov 2012 18:00:35 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<category><![CDATA[Waterloo]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3361</guid>

					<description><![CDATA[<p>Waterloo is an open-source library that can significantly improve Matlab GUI. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics">Waterloo graphics</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/waterloo-graphics-examples" rel="bookmark" title="Waterloo graphics examples">Waterloo graphics examples </a> <small>Some Matlab usage examples for the open-source Waterloo graphics package. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta" rel="bookmark" title="Waterloo graphics beta">Waterloo graphics beta </a> <small>The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment" rel="bookmark" title="Waterloo graphics animation and web deployment">Waterloo graphics animation and web deployment </a> <small>Waterloo graphics can be updated very quickly in Matlab, enabling plot animation; web deployment of the graphics is also possible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity" rel="bookmark" title="Improving graphics interactivity">Improving graphics interactivity </a> <small>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I would like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King&#8217;s College London, who has already <a target="_blank" href="/articles/tag/malcolm-lidierth/">written here</a> in the past. Today Malcolm will describe the Waterloo open-source project and its usage in Matlab.</i></p>
<h3 id="Waterloo">The Waterloo graphics project</h3>
<p>One of Matlab&#8217;s limitations is the quality of its 2D graphics. Plots are more <a target="_blank" href="/articles/plot-linesmoothing-property/">pixellated</a> and <a target="_blank" href="/articles/continuous-slider-callback/">less interactive</a> than some might expect in a modern programming environment.<br />
A recent addition to the open-source <a target="_blank" rel="nofollow" href="http://waterloo.sourceforge.net/">Waterloo</a> graphics library addresses this by providing a pure Java library of 2D graphics functions that can easily be integrated in Matlab. An accompanying Matlab library provides support for these objects in Matlab OOP wrappers. While these do not quite provide a drop-in replacement for Matlab graphics code, in most instances they require very few code line changes to try out the library using existing Matlab code.  Here is a taster of some of the plots presently supported:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><a target="_blank" href="/images/Waterloo_samples.png"><img loading="lazy" decoding="async" alt="Figure 1: Some Waterloo graphs showing a selection of some of the plots available. The list of available plots will grow in time. Click for details" src="https://undocumentedmatlab.com/images/Waterloo_samples_450x392.jpg" title="Figure 1: Some Waterloo graphs showing a selection of some of the plots available. The list of available plots will grow in time. Click for details" width="450" height="392"/></a><figcaption class="wp-caption-text">Figure 1: Some Waterloo graphs showing a selection of some of the plots available. The list of available plots will grow in time. Click for details</figcaption></figure></center><br />
Waterloo is a free, open-source project and it draws upon resources from many other open-source resources: notably the JXGraph class that is part of the <a target="_blank" rel="nofollow" href="http://swingx.java.net/">SwingLabs SwingX project</a> and was originally developed for the &#8220;<a target="_blank" rel="nofollow" href="http://filthyrichclients.org/">Filthy Rich Clients</a>&#8221; book by Chet Haase and Romain Guy. JXGraph formed the basis for some of the core graphics classes in Waterloo.<br />
<span id="more-3361"></span></p>
<h3 id="features">Main features</h3>
<p>Highlights of the project include:</p>
<ul>
<li>Platform-independent, pure Java library callable from any environment that supports a Java Virtual Machine (JVM). So far, I have tested it with Groovy, Java, Matlab, the R statistical environment, Scala and SciLab.</li>
<li>High-speed rendering if you activate the appropriate graphics pipeline – e.g. DirectX for Windows and Quartz for Mac.</li>
<li>Anti-aliased graphics and text together with full support for transparency supported at color, plot and graph levels.</li>
<li>Graphics can be annotated with lines, arrows, text etc that are Java Graphics 2D–based, but also, because the graphs are Swing-based, with other Swing components such as JLabels,  JTextFields etc.</li>
<li>As Waterloo graphs are also Swing components, they too can be added to other Swing components (a Matlab figure for example) as well as to other graphs, for example to create graphical insets.</li>
<li>Multi-layered graphs, with each layer having independent axes.</li>
<p><center><figure style="width: 375px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Figure 2: A multi-layered graph. Each plot has its own graph layer with independent axes." src="https://undocumentedmatlab.com/images/Waterloo_multi-layer.png" title="Figure 2: A multi-layered graph. Each plot has its own graph layer with independent axes." width="375" height="343"/><figcaption class="wp-caption-text">Figure 2: A multi-layered graph. Each plot has its own graph layer with independent axes.</figcaption></figure></center></p>
<li>Built-in mouse interactivity and GUIs for interactive plot editing.</li>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><a target="_blank" href="/images/Waterloo_plot_editor.jpg"><img loading="lazy" decoding="async" alt="Figure 3: A plot editor for a single-layered graph. Java programmers might note here the use of a few custom-designed Swing widgets: a dial that subclasses JSlider and supports multiple-turns, and a color chooser that uses standard names for web colors. Click for details" src="https://undocumentedmatlab.com/images/Waterloo_plot_editor_450x521.jpg" title="Figure 3: A plot editor for a single-layered graph. Java programmers might note here the use of a few custom-designed Swing widgets: a dial that subclasses JSlider and supports multiple-turns, and a color chooser that uses standard names for web colors. Click for details" width="450" height="521"/></a><figcaption class="wp-caption-text">Figure 3: A plot editor for a single-layered graph. Java programmers might note here the use of a few custom-designed Swing widgets: a dial that subclasses <code>JSlider</code> and supports multiple-turns, and a color chooser that uses standard names for web colors. Click for details</figcaption></figure></center></p>
<li>Linear and log axes implemented via Java objects that also format the axes labeling etc.: so for a log axis you have a choice of base 10, 2 and e as well as -log10. Polar plotting is partially implemented and will be improved in later releases.</li>
<li>User-selectable preference settings with a GUI to change them (and save them across sessions).</li>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Waterloo preferences" src="https://undocumentedmatlab.com/images/Waterloo_preferences_450x296.jpg" title="Waterloo preferences" width="450" height="296" /><figcaption class="wp-caption-text">Waterloo preferences</figcaption></figure></center></p>
<li>Export to PDF and SVG files &#8211; and also to the clipboard with preservation of vector graphics quality if your platform supports it. In designing the Java Graphics 2D methods, care has been taken to optimize the grouping of graphics objects to facilitate editing in vector-graphics based packages such as Adobe Illustrator and the open-source InkScape editor. Support is included also for bitmap graphics output to both file and clipboard.</li>
<li>Graphics can be saved to portable XML files. These use the standard <code>java.util.bean.XMLCoder</code>, which is a built-in feature of all JVMs so the files are fully portable. Full serialization/de-serialization is supported so the full state of the graph when it was saved is restored on reloading. Writing and reading of these files has built-in support for gzip compression and decompression of the XML data stream.</li>
<li>An interactive GUI-based &#8220;Graph Explorer&#8221; that can be run as a stand-alone Java executable to view the generated graphs, or be run from a console session (including from the Matlab desktop; note that until I find a fix, Unix-based platforms will need Matlab R2012a or later for this).  You can share XML files with others: they can view and edit them without Matlab.</li>
<li>Tested so far on Windows XP/7 (Oracle JRE 6 &anp; 7), Mac OS Snow Leopard (Apple JRE 6 &amp; OpenJDK 7) and Ubuntu Linux 12.10 (IcedTea OpenJDK JRE 6 &amp; 7).</li>
</ul>
<h3 id="Matlab">Benefits for Matlab users</h3>
<p>For Matlab-users, we can add:</p>
<ul>
<li>Runs &#8220;out-of-the-box&#8221;.  Unzip the distribution and add the Waterloo Matlab Library folder to your path. Running <i>waterloo.m</i> then adds everything needed to the path and sets up the Java dynamic class path for the current Matlab session – so Waterloo is only installed when needed. However, for all JRE 6-based Matlab versions, I would recommend upgrading to the latest JRE 6 release (update 37 at the time of writing): you will get better and faster graphics performance and recent security fixes (including some relevant to the use of XML files as in Waterloo). For best performance on Windows, also edit or create a “java.opts” file to activate DirectX graphics pipeline (then restart Matlab: you cannot alter this setting for the current JVM session). Use: <code>-Dsun.java2d.noddraw=false</code></li>
<li>Integration of the Waterloo and Matlab graphics via Matlab OOP wrappers. You can mix-and-match Waterloo and standard Matlab graphics in a single Matlab figure. </li>
<li>Mixed Matlab and Waterloo graphics are treated specially for serialization. Waterloo creates a folder instead of a single file containing [1] a Matlab .fig file, [2] a Waterloo XML file, and [3] a set of image files &#8211; one for each Matlab axes object. In Matlab, the folder can be re-loaded and both Matlab and Waterloo graphics will be fully de-serialized. Outside of Matlab, e.g. in the Waterloo Graph Explorer, the image files will be used to display Matlab graphs. By default, these images are saved as PNG files but you can install a custom function to generate other formats including SVG (Graph Explorer provides an SVG viewer using <a target="_blank" rel="nofollow" href="http://xmlgraphics.apache.org/batik/">Apache Batik</a>).</li>
<li>The Graph Explorer embeds a copy of the Groovy Console so users can pass variables between the host workspace and the console and use it to run Groovy scripts from Matlab, R, SciLab etc.</li>
<li>Tested variously on Matlab R2008a through R2012b on Mac, Windows and Ubuntu Linux. Although the Matlab OOP uses R2008+ classes, the base Java library could probably be invoked directly from earlier Matlab versions.</li>
<li>Ability to attach Matlab callbacks to the underlying Java objects. That includes property change callbacks for data objects, individual plots and graphs and for their Swing containers.</li>
</ul>
<h3 id="sample">Sample Matlab usage</h3>
<p>I will finish with a simple example of mixing Matlab and Waterloo graphics:</p>
<pre lang='matlab'>
% Create some data
t = 0 : .035 : 2*pi;
[x,y] = pol2cart(t, sin(2*t).*cos(2*t));
% Now do the plotting
hFig = GXFigure(); % Create Waterloo-enabled Matlab figure
ax1 = subplot(1,  2, 1); % Create Matlab axes
ax2 = subplot(hFig, 1, 2, 2); % Create Waterloo "axes"
scatter(ax1, x, y); % Matlab scatter plot
scatter(ax2, x, y); % Waterloo scatter plot
set(gcf, 'Units', 'normalized', 'Position', [0.1 0.1 0.8 0.8]);
</pre>
<p>Here is the output:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><a target="_blank" href="/images/Waterloo_mixed.png"><img loading="lazy" decoding="async" alt="Figure 5: Mixed Matlab and Waterloo graphics in a single Matlab figure. Click for details" src="https://undocumentedmatlab.com/images/Waterloo_mixed_450x324.jpg" title="Figure 5: Mixed Matlab and Waterloo graphics in a single Matlab figure. Click for details" width="450" height="324" /></a><figcaption class="wp-caption-text">Figure 5: Mixed Matlab and Waterloo graphics in a single Matlab figure. Click for details</figcaption></figure></center><br />
Next week, I will give more Matlab code examples.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/waterloo-graphics">Waterloo graphics</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/waterloo-graphics-examples" rel="bookmark" title="Waterloo graphics examples">Waterloo graphics examples </a> <small>Some Matlab usage examples for the open-source Waterloo graphics package. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-beta" rel="bookmark" title="Waterloo graphics beta">Waterloo graphics beta </a> <small>The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics-animation-web-deployment" rel="bookmark" title="Waterloo graphics animation and web deployment">Waterloo graphics animation and web deployment </a> <small>Waterloo graphics can be updated very quickly in Matlab, enabling plot animation; web deployment of the graphics is also possible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity" rel="bookmark" title="Improving graphics interactivity">Improving graphics interactivity </a> <small>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/waterloo-graphics/feed</wfw:commentRss>
			<slash:comments>39</slash:comments>
		
		
			</item>
		<item>
		<title>Using Groovy in Matlab</title>
		<link>https://undocumentedmatlab.com/articles/using-groovy-in-matlab?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-groovy-in-matlab</link>
					<comments>https://undocumentedmatlab.com/articles/using-groovy-in-matlab#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 04 Jul 2012 19:14:02 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2988</guid>

					<description><![CDATA[<p>Groovy code can seamlessly be run from within Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-groovy-in-matlab">Using Groovy in Matlab</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface" rel="bookmark" title="JMI &#8211; Java-to-Matlab Interface">JMI &#8211; Java-to-Matlab Interface </a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab" rel="bookmark" title="Using SQLite in Matlab">Using SQLite in Matlab </a> <small>SQLite databases can be accessed in a variety of different ways in Matlab. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I would like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King&#8217;s College London, who has already <a target="_blank" href="/articles/tag/malcolm-lidierth/">written here</a> in the past. Today Malcolm will explain the basics of using Groovy code within Matlab.</i><br />
Readers of this blog are likely to be familiar with calling Java from within Matlab code and/or writing custom Java code for Matlab use. But, Java is only one of many programming languages that can use the Java Virtual Machine. Here, I&#8217;d like to draw Matlab-users&#8217; attention to another: Groovy.<br />
<span class="alignright"><img loading="lazy" decoding="async" title="Groovy logo" src="https://undocumentedmatlab.com/images/groovy-logo.png" alt="Groovy logo" width="227" height="112"/></span> <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Groovy_%28programming_language%29">Groovy</a> is a superset of Java that compiles to Java byte-code and seamlessly integrates with existing Java code. So seamlessly, in fact, that you can mix-and-match Java and Groovy syntax in a single file or method. This means that you can call Groovy classes from Matlab just as though they were Java classes: Matlab will see no difference.<br />
Most IDEs support Groovy and include the necessary files – IntelliJ seems particularly good for Groovy development. Groovy is also available separately at <a target="_blank" rel="nofollow" href="http://groovy.codehaus.org/Download">http://groovy.codehaus.org/Download</a>. Use Groovy 1.8.6 or earlier, not the latest 2.0 version (* see <a href="/articles/using-groovy-in-matlab/#Groovy2.0">below</a>).<br />
All that is needed to run Groovy in Matlab is to include its jar files on your Matlab javaclasspath, by using Matlab&#8217;s <i><b>javaaddpath</b></i> function to add to the dynamic classpath, or by adding the jar locations to the classpath.txt file (the static classpath, which is generally better).<br />
To illustrate a few of its features, below is a rough-and-ready static method in Groovy to return a factorial:</p>
<pre lang='groovy'>
package Examples
class StaticLib {
   static factorial(n){
      def fact=1.0
      for (def k=1; k< =n; k++)
         fact*=k
      return fact
   }
}
</pre>
<p>Java programmers will note there are no <code>public</code> keywords: in Groovy public is the default. Next the method declaration has no return type. Neither does the input <code>n</code>. In Groovy, typing is optional. This is exploited on the next line, where <code>fact</code> is declared using the <code>def</code> keyword. Groovy will determine its type at runtime much as Matlab does for variables. The same is true for the loop control variable <code>k</code>.<br />
To run the code at the Matlab command prompt, use commands as you would for Java e.g:</p>
<pre lang='matlab'>
>> import Examples.StaticLib
>> StaticLib.factorial(40)
>> StaticLib.factorial(int64(40))
>> StaticLib.factorial(java.math.BigInteger(40))
</pre>
<p>all produce:</p>
<pre lang='matlab'>
ans =
815915283247897734345611269596115894272000000000.0
</pre>
<p>This is an exact, and correct, result because Groovy instantiated <code>fact</code> as a <code>java.math.BigDecimal</code> when it was initialized with a floating-point value. Note also, that Groovy&#8217;s dynamic typing meant only one method was needed– not one for every possible class of input. With Groovy, you need to write much less code. (Caution: running this code with very large n will work, but slowly, and potentially take up all available memory to store the result).<br />
The small typing change below makes a substantial difference to the code&#8217;s operation:</p>
<pre lang='groovy'>
package Examples
   class NewLib {
      def factorial = {n ->
      def fact = 1.0
      for (def k = 1; k < = n; k++)
         fact *= k
      return fact
   }
}
</pre>
<p>Here, factorial is a property, not a method, of the class and its contents are the code – in Groovy this is a closure (in Matlab it would be called an anonymous function).<br />
Create an instance of the <code>NewLib</code> class in Matlab, call the <i>get</i> method on the <code>factorial</code> property and run the code in Matlab as follows:</p>
<pre lang='matlab'>
>> myObj=Examples.NewLib();
>> func=myObj.getFactorial();
>> func.call(40)
ans =
815915283247897734345611269596115894272000000000.0
</pre>
<p>Using Groovy saved a lot of work: there was no need to write a no argument constructor or a <i>getFactorial()</i> method. Groovy did that automatically.<br />
Here is another code snippet where Groovy&#8217;s dynamic typing makes it look much more like Matlab than Java:</p>
<pre lang='groovy'>
for (obj in props) {
   switch (obj.key) {
      …
      case "Alpha":
      case "EdgeColor":
      case "LineColor":
      case "XData":
      case "YData":
      case "ZData":
      plot.("set" + obj.key)(props.(obj.key))
      break
      …
   }
}
</pre>
<p>props is a <code>LinkedHashMap</code>. We start by running through each of the entries in this map in a loop using:</p>
<pre lang='groovy'>for (obj in props)</pre>
<p>Each entry is assigned to <code>obj</code> in turn. Again, we let Groovy determine the class of <code>obj</code> dynamically &#8211; it will be of class <code>java.util.LinkedHashMap$Entry</code>, but we do not need to worry about that detail.<br />
For each entry we retrieve the key and use that as the variable for the <code>switch</code> block. In this case, the keys are all strings and, in Groovy, strings can be used in <code>case</code> statements (Java 7 would be needed for that if the code were written in Java; note that Java 7 is still not integrated in Matlab as of this date).<br />
Within the switch block, the code invokes a setter on an object called <code>plot</code>. Rather than write separate lines for each possible property in the key list, one line is enough:</p>
<pre lang='groovy'>plot.("set" + obj.key)(props.(obj.key))</pre>
<p>The key string is pre-pended with &#8220;set&#8221; and the corresponding method is invoked passing the value from the <code>LinkedHashMap</code> entry as input – so a particular iteration of the loop, this might equate for example to <code>plot.setAlpha(0.5)</code><br />
For a Matlab programmer who is put off from delving into Java because of the tedious boiler-plate code it requires, Groovy may be an attractive alternative. Groovy also has many powerful features for handling regular expressions, a set of builder classes (for example a thread-safe <code>SwingBuilder</code> class), writing domain specific languages and for meta-object programming including run-time injection of new methods. There is also a growing set of Groovy <a target="_blank" rel="nofollow" href="http://groovy.codehaus.org/Modules">plugin modules</a>.<br />
Not all Java programmers like Groovy. The dynamic features inevitably create run-time overheads and mean that type-mismatches that would be detected at compile-time in Java may produce run-time exceptions with Groovy, but Groovy 2.0 addresses some of these issues by introducing new <a target="_blank" rel="nofollow" href="http://www.infoq.com/articles/new-groovy-20">compiler annotations</a>. My own use of it has been limited, partly because of these issues: I have used it to create a static library to link Matlab, R, SciLab etc to a graphics package written in Java. The dynamic features of Groovy have been useful there to reduce the work involved.<br />
<a id="Groovy2.0"></a><br />
<i>* Note: Groovy 2.0 was released 28.06.2012. Initial experiments suggest it does not work within Matlab, perhaps because of version clashes with jars on the Matlab static class path.</i><br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<div style="background-color: rgb(255, 255, 0);">
Note: in 21-23 August 2012, I (Yair) will present advanced Matlab training courses in <b>Geneva</b>, Switzerland. The planned topics are:</p>
<ul>
<li>Aug 21 &#8211; <a target="_blank" href="/courses/Matlab_Performance_Tuning_Course.pdf">Matlab performance tuning</a></li>
<li>Aug 22 &#8211; <a target="_blank" href="/courses/Advanced_Matlab_GUI_Course_1d.pdf">Advanced Matlab GUI</a></li>
<li>Aug 23 &#8211; <a target="_blank" href="/courses/Using_Java_in_Matlab_Course.pdf">Using Java in Matlab</a> (inc. extra advanced GUI)</li>
</ul>
<p>Anyone interested please <a href="mailto:%20altmany%20@gmail.com?subject=Matlab%20courses&amp;body=Hi%20Yair,%20&amp;cc=;&amp;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab courses&amp;body=Hi Yair, '); return false;">email me</a> (altmany at gmail dot com) for more details.
</div>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-groovy-in-matlab">Using Groovy in Matlab</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface" rel="bookmark" title="JMI &#8211; Java-to-Matlab Interface">JMI &#8211; Java-to-Matlab Interface </a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab" rel="bookmark" title="Using SQLite in Matlab">Using SQLite in Matlab </a> <small>SQLite databases can be accessed in a variety of different ways in Matlab. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/using-groovy-in-matlab/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Controlling callback re-entrancy</title>
		<link>https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=controlling-callback-re-entrancy</link>
					<comments>https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Aug 2011 18:00:57 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2403</guid>

					<description><![CDATA[<p>Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy">Controlling callback re-entrancy</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/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/continuous-slider-callback" rel="bookmark" title="Continuous slider callback">Continuous slider callback </a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I&#8217;d like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King&#8217;s College London. Malcolm is well known in the Matlab-Java community for his <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15580-using-java-swing-components-in-matlab">jcontrol utility</a>. Some months ago, I mentioned his work on another File Exchange contribution, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilities">MUtilities</a> when I discussed <a target="_blank" href="/articles/transparent-matlab-figure-window/">transparent Matlab figure windows</a>. Today, Malcolm discusses one of his lesser-known but extremely important <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">isMultipleCall utility</a>.</i><br />
Every now and again, a very simple bit of code turns out to be more useful than the author initially imagined. Something I have repeatedly used is the <i><b>isMultipleCall</b></i> function which I <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">posted</a> to MATLAB Central&#8217;s File Exchange a year or so ago.<br />
The <i><b>isMultipleCall</b></i> function uses fully-documented pure-MATLAB to extend the control that can be achieved over callbacks.<br />
Here was the problem: I had a modular system built in MATLAB which allowed third-party developers to add their own plugins. I wanted a mechanism to force the dismissal (&#8220;bail-out&#8221;) of a callback even when the <b>Interruptible</b> property of the parent object was set to &#8216;on&#8217;. Such callback re-entrancy issues are common for rapidly-firing events, and debugging and fixing them is usually <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/5809-how-to-implement-a-speed-limit-for-gui-button-press">not easy</a>.<br />
The callback&#8217;s dismissal code would need to be fast because it might be called many dozens of times, e.g. in a <b>WindowButtonMotion</b> callback. An obvious approach was to check the function call stack using MATLAB&#8217;s <i><b>dbstack</b></i> function. Although, at first, this seemed likely to be too slow, profiling showed it was not – taking &lt; 40&micro;sec per call &#8211; and within a <b>WindowButtonMotion</b> callback in a real GUI, I could not perceive any slowing of the code.<br />
Here is the function:</p>
<pre lang='matlab'>
function flag=isMultipleCall()
  flag = false;
  % Get the stack
  s = dbstack();
  if numel(s)< =2
    % Stack too short for a multiple call
    return
  end
  % How many calls to the calling function are in the stack?
  names = {s(:).name};
  TF = strcmp(s(2).name,names);
  count = sum(TF);
  if count>1
    % More than 1
    flag = true;
  end
end
</pre>
<p>With <i><b>isMultipleCall</b></i> invoked from another function (see note below), <i><b>dbstack</b></i> will return a structure with a minimum of 2 elements – the first relating to <i><b>isMultipleCall</b></i> itself and the second to the calling function. So with <i><b>numel</b></i>(s) &lt;= 2, there can be no multiple calls and we can return false immediately thus saving time in doing any further testing.  For <i><b>numel</b></i>(s) &gt; 2 we simply check to see whether the calling functions referenced in s(2) appears anywhere else on the stack. If it does, then we return true; otherwise false.<br />
Then, in our callback code we simply use:</p>
<pre lang='matlab'>if isMultipleCall();  return;  end</pre>
<p>If this line is placed first in the callback function code, it essentially mimics the behavior that you might expect after setting the <b>Interruptible</b> property of the event firing object to &#8216;off&#8217;. Adding a <i><b>drawnow()</b></i> at the end of the callback will ensure that any waiting callbacks in the queue are dismissed:</p>
<pre lang='matlab'>
function MyCallback(hObj, EventData)
  % Quick bail-out if callback code is called before another has ended
  if isMultipleCall();  return;  end
  ...  % do some actual callback work here
  drawnow();
end
</pre>
<p>There are several ways in which <i><b>isMultipleCall</b></i> can extend the standard MALAB functionality. First, by moving <i><b>isMultipleCall</b></i> reference from the first line of the callback we can create both an interruptible and an uninteruptible code block, e.g.</p>
<pre lang='matlab'>
function MyCallback(hObj, EventData)
  %Code Block 1
  ...
  if isMultipleCall();  return;  end
  %Code Block 2
  ...
  drawnow();
end
</pre>
<p>Second, as <i><b>isMultipleCall</b></i> controls the callbacks  &#8211; not the objects that trigger them &#8211; we can individually control the callbacks of objects which fire multiple events. That is particularly useful with Java components, which gives a third extension – <i><b>isMultipleCall</b></i> can be used in any function: not just the callbacks of standard MATLAB components, but also of Java or COM components.<br />
 <br />
Finally, as the callback, not the object is being controlled, we can control a callback that may be shared between multiple objects e.g. a menu component and a toolbar button.<br />
Not bad for 13 lines of code.<br />
Note: <i><b>isMultipleCall</b></i> must be called from a function, not from a string in the callback property.<br />
Do you have any other favorite mechanism for controlling callback re-entrancy? If so, please <a href="/articles/controlling-callback-re-entrancy/#respond">post a comment</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy">Controlling callback re-entrancy</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/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/continuous-slider-callback" rel="bookmark" title="Continuous slider callback">Continuous slider callback </a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy/feed</wfw:commentRss>
			<slash:comments>17</slash:comments>
		
		
			</item>
		<item>
		<title>Transparent Matlab figure window</title>
		<link>https://undocumentedmatlab.com/articles/transparent-matlab-figure-window?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=transparent-matlab-figure-window</link>
					<comments>https://undocumentedmatlab.com/articles/transparent-matlab-figure-window#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Apr 2011 23:22:38 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Malcolm Lidierth]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2246</guid>

					<description><![CDATA[<p>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window">Transparent Matlab figure window</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/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>
<li><a href="https://undocumentedmatlab.com/articles/disable-entire-figure-window" rel="bookmark" title="Enable/disable entire figure window">Enable/disable entire figure window </a> <small>Disabling/enabling an entire figure window is impossible with pure Matlab, but is very simple using the underlying Java. This article explains how....</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Every now and then, a user asks whether it is possible to make an entire Matlab window transparent (<a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/280394">example</a>). This could be used, for example, for window fade-in/fade-out effects. The short answer is that there is no supported way of doing this with pure documented Matlab, but it is trivially easy to achieve using just a bit of Java magic powder (surprise, surprise).</p>
<h3 id="transparency">Matlab figure window transparency</h3>
<p>Following an idea I got from Malcolm Lidierth&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilities">MUtilities</a> submission on the Matlab File Exchange, the solution for setting Matlab figure window transparency is quite simple: Get the figure&#8217;s underlying Java window reference handle, as in <a target="_blank" href="/articles/disable-entire-figure-window/">last week&#8217;s</a> article. Then use Java&#8217;s <a target="_blank" rel="nofollow" href="http://www.pushing-pixels.org/2008/02/27/translucent-and-shaped-windows-in-core-java.html"><i>setWindowOpacity</i> method</a> to set the window&#8217;s transparency value. Actually, <i>setWindowOpacity</i> sets the opacity level, rather than transparency, but they are obviously complementary and I personally find &#8220;transparency&#8221; to be more easily understandable.<br />
By default, windows are created with an opacity of 1.0 (= not transparent). They can be set to any floating-point value between 0.0-1.0, where an opacity of 0.0 means full transparency, and any value in between means partial transparency (i.e., translucency):</p>
<pre lang='matlab'>
jFigPeer = get(handle(gcf),'JavaFrame');
jWindow = jFigPeer.fFigureClient.getWindow;
com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,0.7)
</pre>
<p><center><figure style="width: 500px" class="wp-caption aligncenter"><a target="_blank" rel="nofollow" href="https://undocumentedmatlab.com/images/setFigTransparency.png"><img decoding="async" alt="Semi-transparent (translucent) Matlab figure (click to enlarge)" src="https://undocumentedmatlab.com/images/setFigTransparency.png" title="Semi-transparent (translucent) Matlab figure (click to enlarge)" width="500" /></a><figcaption class="wp-caption-text">Semi-transparent (translucent) Matlab figure (click to enlarge)</figcaption></figure></center><br />
Similarly, you can set the entire Matlab Desktop&#8217;s transparency/opacity value:</p>
<pre lang='matlab'>
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance.getMainFrame;
com.sun.awt.AWTUtilities.setWindowOpacity(jDesktop, 0.8);
</pre>
<p>Note that the <code>com.sun.awt.AWTUtilities</code> class also enables <a target="_blank" rel="nofollow" href="http://today.java.net/pub/a/today/2008/03/18/translucent-and-shaped-swing-windows.html">other GUI effects</a> that would make a Matlab GUI developer&#8217;s mouth to start drooling: shaped windows, per-pixel transparency values, mirroring/reflection, window shadows, <a target="_blank" rel="nofollow" href="http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/">gradients</a> etc. Perhaps I&#8217;ll explore their adaptation for Matlab figures someday.</p>
<h3 id="Fade">Fade-in / fade-out</h3>
<p>Window fade-in/fade-out effects can easily be achieved using transparency: Simply invoke the <i>setWindowOpacity</i> method several times, with progressively higher or lower values. This is easily done in a simple blocking loop. For example, to fade-out a window:</p>
<pre lang='matlab'>
for stepIdx = 1 : 5
   newAlpha = 1.0 - 0.2*stepIdx;
   com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,newAlpha);
   jWindow.repaint;
   pause(0.2);  % seconds
end
</pre>
<p><center><figure style="width: 300px" class="wp-caption aligncenter"><img decoding="async" alt="Gradual window fade-out" src="https://undocumentedmatlab.com/images/transparent_figure_animated.gif" title="Gradual window fade-out" width="300" /><figcaption class="wp-caption-text">Gradual window fade-out</figcaption></figure></center><br />
A more general example dynamically computes the opacity step size/duration and also enables non-blocking fade effects using an asynchronous timer:</p>
<pre lang='matlab'>
% Compute the required opacity-setting steps
fadeDuration = 1.5;  % seconds
oldAlpha = com.sun.awt.AWTUtilities.getWindowOpacity(jWindow);
newAlpha = 0.0;
deltaAlpha = newAlpha - oldAlpha;
maxStepAlpha = 0.03;
steps = fix(abs(deltaAlpha) / maxStepAlpha) + 1;
stepAlpha = deltaAlpha / steps;
stepDuration = fadeDuration / (steps-1);
% If blocking, do the fade effect immediately
if blockingFlag || steps==1
   for stepIdx = 1 : steps
      newAlpha = oldAlpha + stepAlpha*stepIdx;
      com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,newAlpha);
      jWindow.repaint;
      if stepIdx < steps,  pause(stepDuration);  end
   end
else
   % non-blocking: fade in/out asynchronously using a dedicated timer
   start(timer('ExecutionMode','fixedRate', 'Period',0.1, 'TasksToExecute',steps, ...
               'TimerFcn', {@timerFcn,jWindow,oldAlpha,stepAlpha}));
end
% Timer function for non-blocking fade-in/fade-out effect
function timerFcn(hTimer,eventData,jFrame,currentAlpha,stepAlpha)  %#ok<inusl> eventData
  stepIdx = hTimer.TasksExecuted;
  newAlpha = currentAlpha + stepAlpha*stepIdx;
  com.sun.awt.AWTUtilities.setWindowOpacity(jFrame,newAlpha);
  jFrame.repaint;
  if stepIdx == hTimer.TasksToExecute
      stop(hTimer);
      delete(hTimer);
  end
end  % timerFcn
</pre>
<p>Of course, you can also fade-in/out to intermediate values such as 0.3 or 0.8. If you fade-out completely (i.e., to a value of 0.0), it might be a good idea to actually <i><b>close</b></i> the figure window once it gets the totally-transparent value of 0.0.<br />
I&#8217;ve prepared a Matlab utility that contains all these options, including optional blocking/non-blocking fade effects, in my <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/30583-setfigtransparency-set-figure-transparency-fading"><i><b>setFigTransparency</b></i> utility</a>, which is available for download on the Matlab File Exchange. You may also wish to use Malcolm Lidierth&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilities">MUtilities</a>, which also has similar functionalities (plus some other goodies).</p>
<h3 id="Limitations">Limitations</h3>
<p>Setting a figure window&#8217;s transparency requires using Java Run-time Engine (JRE) 1.6.0_10 (also called &#8220;Java 6 update 10&#8221;) or higher. This means that it&#8217;s supported on Matlab release 7.9 (R2009b) and higher by default, and on earlier releases using a JRE retrofit.<br />
If you are using an earlier Matlab release, consider a retrofit of JRE 1.6.0_10 or any later version (e.g., the latest available version today is 1.6 update 24). The JRE can be downloaded from <a target="_blank" rel="nofollow" href="http://java.com/en/download/manual.jsp">here</a>, and you can configure Matlab to use it according to the instructions <a target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-1812J/">here</a>. As noted, Matlab R2009b (7.9) and onward, at least on Microsoft Windows, pre-bundle a JRE version that does support transparency/opacity and so do not require a retrofit.<br />
You can check your current Java version in Matlab as follows:</p>
<pre lang='text'>
>> version -java
ans =
Java 1.6.0_17-b04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode
</pre>
<p>Unfortunately, Matlab plot axes cannot be made transparent. If you have any axes in your GUI, the axes area will simply appear as a shaded axes, whose intensity depends on the selected alpha (transparency) value; the contents beneath the window will not be merged in the axes area as it is in the non-axes areas.<br />
Finally, note that <code>com.sun.awt.AWTUtilities</code> is itself an undocumented Java class. It is bundled with the standard Java release since 2008 (1.6.0_10), and yet is not part of the official release because its API has not yet settled. In fact, in the upcoming Java 7 release, which is expected in a few months, and which I expect to be available in Matlab sometime in 2012, the set of transparency/opacity methods have <a target="_blank" rel="nofollow" href="http://www.pushing-pixels.org/2009/05/03/translucent-and-shaped-windows-in-jdk-7.html">migrated</a> to the fully-documented <code>java.awt.Window</code> class.</p>
<h3 id="blurring">Blurred figure window</h3>
<p>So here&#8217;s a riddle for you: using figure window transparency, can you guess how to make a Matlab figure appear blurred for <a target="_blank" href="/articles/disable-entire-figure-window/">disabled figures</a> (see the screenshot there)? There are several possible ways to do this &#8211; can you find the simplest? The first one to <a target="_blank" href="/articles/transparent-matlab-figure-window/#respond">post a comment</a> with a correct answer gets a smiley&#8230; My answer will appear in next week&#8217;s article.</p>
<h3 id="upgrade">Upgraded website</h3>
<p>Also, did you notice my new website design? It&#8217;s supposed to be much more readable (yes &#8211; also on <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/2010/05/24/introducing-matlab-mobile-%E2%80%93-an-iphone-app-to-connect-remotely-to-your-matlab/#comments">Android</a>&#8230;). It now also runs on a multi-server cloud, which means more stability and faster response times. Do you like the new design? hate it? I would love to hear your feedback via <a target="_blank" href="/articles/transparent-matlab-figure-window/#respond">comment</a> or <a href="mailto:%20altmany%20@gmail.com?subject=Undocumented%20Matlab&amp;body=Hi%20Yair,%20&amp;cc=;&amp;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Undocumented Matlab&amp;body=Hi Yair, '); return false;">email</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window">Transparent Matlab figure window</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/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>
<li><a href="https://undocumentedmatlab.com/articles/disable-entire-figure-window" rel="bookmark" title="Enable/disable entire figure window">Enable/disable entire figure window </a> <small>Disabling/enabling an entire figure window is impossible with pure Matlab, but is very simple using the underlying Java. This article explains how....</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/transparent-matlab-figure-window/feed</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
			</item>
	</channel>
</rss>
