File Exchange Pick of the Week

November 23rd, 2011

Scrolling Figures & GUIs

Ameya's pick this week is Scrollsubplot by Bjorn Gustavsson.

This week, it's an early post because of Thanksgiving holiday here in the U.S.

Hello MATLAB fans! My name is Ameya and I'm a colleague of Jiro and Brett at MathWorks. I primarily support MATLAB users in financial services but I'm personally very interested in tool building, visualization and GUIs. This is my first pick as a guest on this blog so I hope you enjoy it.

If you are familiar with any of my submissions, you might know that I'm a big fan of generalizing built-in MATLAB functions with wrappers to offer more control or expanded functionality. My pick this week does exactly that. It extends the subplot command to create an infinite canvas of plots with a scroll bar. This can be very useful if you have many visualizations to display in a single figure window or GUI but a limited amount of screen real estate. Best of all, because it works just like subplot, you don't need to learn new syntax or modify a lot of existing code. Reviewer Telmo Amaral perhaps says it best: "This function did precisely what I needed in the easiest possible way: just had to replace all the calls to subplot with calls to scrollsubplot."

For example, suppose we need to display 3 rows of plots on a figure but really only have enough room for 2 rows on screen at one time. We can set up just such a canvas with scrollsubplot:

% Create a standard 2-row view, similar to _subplot_
scrollsubplot(2,1,1); plot(cumsum(randn(200,10)));
scrollsubplot(2,2,3); plot(rand(10,1), rand(10,1), '^');
scrollsubplot(2,2,4); hist(randn(100,1));

% Create axes outside the visible area and generate a scroll bar to bring
% these axes into view
scrollsubplot(2,2,5); imagesc(magic(16));
scrollsubplot(2,2,6); pie(rand(10,1));

The figure can be scrolled interactively or with the supporting scroll function. The final result looks something like the following:

Bjorn adds the convenience of using the arrow and the page up/down keys to scroll through the canvas of axes. I also like how he sets up all of the position offset constants at the beginning of his function so that one can easily customize the spacing between subplots.

Comment

Let us know what you think here or leave a comment for Bjorn.


Get the MATLAB code

Published with MATLAB® 7.13

November 18th, 2011

Errorbar with Adjusted Tick Size

Jiro's pick this week is Errorbar with Adjusted Tick by Arnaud Laurent.

Just this week, I got a comment from Felipe on a guest post ("Making Pretty Graphs") that I did on Loren's blog. He pointed out this function by Arnaud that helps adjust the size of the horizontal ticks at the top and bottom of the errorbars that I had to fix manually in the post. Thanks Felipe for the tip!

The errorbar automatically determines the tick size based on the limits of the axes, and there is no simple option to change that. However, the function can return a handle to errorbarseries, and you can modify the tick size by digging into its properties. That's what I did in my blog post. Now, it's even easier with Arnaud's errorbar_tick. I echo Felipe's comment on the entry page that it's nice how errorbar_tick works on the handle returned by the errorbar function, rather than recreating the functionality available in errorbar.

Create a standard errorbar plot:

x = 1:10;
y = sin(x);
e = std(y)*ones(size(x));
h = errorbar(x,y,e, 'o-');
set(h, 'MarkerSize', 10, 'MarkerFaceColor', [.3 1 .3], ...
    'MarkerEdgeColor', [0 .5 0]);

Apply errorbar_tick to increase tick size:

errorbar_tick(h, 30);

Comments

Let us know what you think here or leave a comment for Arnaud.


Get the MATLAB code

Published with MATLAB® 7.13

November 11th, 2011

3D Polar Plotting

Brett's Pick this week is polarplot3d, by Ken Garrard.

I don't often get suggestions from readers of this blog for which files to feature. Typically, I just focus on files that I've found, or that look useful or intriguing based on descriptions and comments. This week is different; I received an email from long-time MATLABber Yair Altman, suggesting that I consider Ken's file as a Pick of the Week. Yair is one of the most downloaded authors on the MATLAB Central File Exchange (and is recognized as an expert in "undocumented MATLAB.") So I was quite pleased to see his recommendation come in, and happier still to be able to feature it.

Ken's code allows you to easily plot a 3D surface from polar coordinate data. With an easy-to-use syntax, his code supports the creation of several standard (and some custom) plot types, including surface plots (with and without lines, and with and without contours) and mesh plots (with and without contours). You can also specify lots of different parameters, including the polar direction (cw or ccw), the type of interpolation, and the color scheme. Optional outputs readily provide the Cartesian locations corresponding to input polar coordinates (T,R,Zp). To illustrate, here is Ken's own example from his code:

[t,r] = meshgrid(linspace(0,2*pi,361),linspace(-4,4,101));
[x,y] = pol2cart(t,r);
P = peaks(x,y);                       % peaks function on a polar grid

figure('color','white');              % draw 3d polar plot
polarplot3d(P,'PlotType','surfn','PolarGrid',{4 24},'TickSpacing',8,...
    'AngularRange',[30 270]*pi/180,'RadialRange',[.8 4]);

% set plot attributes
set(gca,'DataAspectRatio',[1 1 10],'View',[-12,38],...
    'Xlim',[-4.5 4.5],'Xtick',[-4 -2 0 2 4],...
    'Ylim',[-4.5 4.5],'Ytick',[-4 -2 0 2 4]);
title('polarplot3d example');

As always, comments to this blog post are welcome. Or leave a comment for Ken here. And if you have any suggestions for files (other than your own, please) that you think should be considered as a future Pick of the Week, please email me! I can be reached directly at:

char(cumsum(...
    [98 16 -13 15 0 -70 69 -11 7 -10 7 7 -4 -1 ...
    -46 45 -12 19 -12 15 -8 3 -7 8 -69 53 12 -2]));


Get the MATLAB code

Published with MATLAB® 7.13

November 4th, 2011

Happy (belated) Halloween!

Michael's pick this week is Batman Equation: The Legend by Mingjing Zhang.

This posting comes a bit too late for a proper Halloween celebration, but I'm not one to let that get in the way of a fun little file exchange submission. Plain and simple, it's Batman's logo in MATLAB form!

In late July of 2011, an odd little equation started to appear on the internet. With clever use of terms in the form , its creator was able to construct an effectively piecewise outline using a single implicit equation.

Mingjing provides a useful implementation of this equation. To overcome the fact that implicit equations can be tricky to plot using a computer, he breaks it down into its six constituent parts. Different visualizations allow you to see the pieces separately or to visualize the final product in all its glory:

plotbatmaneq

Mingjing seems to enjoy using MATLAB as more than a numerical analysis tool-- I'm planning to soon download and play his Stellaria, humbly dubbed "the best MATLAB shooting game ever"!

Let us know what you think here.


Get the MATLAB code

Published with MATLAB® 7.13

October 28th, 2011

Numerical methods on piecewise-continuous functions

Jiro's pick this week is Chebfun v2 by the Chebfun Team.

Contents

Thorough Documentation

I was initially drawn to this entry because of the comprehensive documentation that was included with it. You can directly view it from the File Exchange page:

Their user's guide is extremely detailed and helpful. I had very little prior knowledge of the concepts covered by this tool, but after reading through it, I've come to appreciate the usefulness and the power of the tool. They created the guide using MATLAB's publishing functionality, which is an extremely effective way of providing documentation and examples for the end-users, because of the ability to intermix code, figures, explanatory text, and equations. Find more information about publish from this page on our Academic website.

Chebfun Function

Now, let's take a look at the tool.

Borrowing the words from their documentation, a chebfun is a function of one variable defined within a particular interval. It allows you to perform symbolic-like operations with the performance of numerics. The underlying implementation of chebfun is based on the mathematical fact that smooth functions can be represented very efficiently by expansions in Chebyshev polynomials, similar to how Fourier series work with smooth periodic functions. By decomposing a function into these polynomial interpolants, many mathematical operations can be carried out efficiently.

Let's define a chebfun for within the interval [0 2].

f = chebfun(@(x) sin(x)+cos(3.3*x)-0.5*x.^2, [0 2])
f = 
   chebfun column (1 smooth piece)
          interval          length   values at Chebyshev points
(        0,        2)        21            1          1          1 ...      -0.14
 

You can see that this function is represented by 21 points, i.e. a polynomial of degree 20. Let's plot it, along with the intermediate points (Chebyshev points)

plot(f, '.-')

This chebfun representation can be evaluated at arbitrary points:

f([0.2, 0.5, 0.9, 1.5, 1.85])
ans =
    0.9687    0.2753   -0.6070    0.1079    0.2342

To calculate the integral from 0 to 2,

sum(f)
ans =
    0.1772

The roots can be found by

r = roots(f)
hold on
plot(r, f(r), 'ro', 'MarkerFaceColor', 'r');
r =
    0.5953
    1.4429
    1.9557

By now, you probably have noticed that chebfun is implemented using object-oriented programming, with a number of overloaded methods, such as plot, sum, and roots.

I can say for sure that I'm not doing justice to this entry with this short blog post. I've just scratched the surface with what could be done with this tool. I highly encourage you to take a look through the documentation and give it a try. On the download page, it says that they have Version 4 available for download off of their university website. I'm hoping that they will also update the version on the File Exchange.

Comments

Let us know what you think here or leave a comment for the Chebfun Team.


Get the MATLAB code

Published with MATLAB® 7.13

October 21st, 2011

Drawing Ellipses

Brett's Pick this week is ellipse, by David Long.

I've blogged before about fitting circles, and about simply drawing circles. And I've blogged about fitting ellipses. I like the general utility of functionality that facilitates those common tasks. Today, I complete the suite with a Pick that trivializes the drawing of an ellipse.

David's syntax is quite nice:

h=ellipse(ra,rb,ang,x0,y0,C,Nb);

There are defaults for all of the inputs (you'd get a circle of radius 1, plotted at [0,0]), but most usefully, you would specify, at a minimum, the semi-major (ra) and semi-minor (rb) axes lengths, the desired angle, and the coordinates of the center (plus, optionally, the color and the number of points used in the construction).

Remember Spirograph? Here's a fun little graphic I created using David's ellipse function, and another previous pick, distinguishable_colors:

colors = distinguishable_colors(20);
n = 20;
angles = linspace(0,2*pi,n);
h = zeros(n,1);
for ii = 1:n
   h(ii) = ellipse(2,1,angles(ii),0,0,colors(ii,:));
end
axis equal
axis off
set(h,'linewidth',2)
set(gcf,'color','w')

As always, comments to this blog post are welcome. Or leave a comment for David here.


Get the MATLAB code

Published with MATLAB® 7.13

October 14th, 2011

Traveling Salesman Problem – Genetic Algorithm

Will's picks this week is Traveling Salesman Problem - Genetic Algorithm by Joseph Kirk.

I stumbled upon this submission purely by accident while looking for something completely unrelated. It just goes to show that you never know what goodies you'll discover on the File Exchange. The function converges on the optimal solution to the traveling salesman problem by employing a genetic algorithm. Ok, what does that mean, exactly?

The traveling salesman has a set of cities he or she wishes to visit. The salesman wants to visit each city only once before returning to the city of embarkation. In which order should the salesman visit the cities to minimize the distance traveled? Well, if there are a handful of cities, you could probably figure this out through inspection. But what do you do when there are hundreds of cities to visit?

There are many approaches to solving this problem. In Joseph's case, he opted for a genetic algorithm. He creates a population of possible routes, determines the best route in the population, mutates the best route to get new samples in his population, and repeats the process. He accomplishes all of this with core MATLAB commands. If you're interested in additional capabilities in this arena, check out the Global Optimization Toolbox.

What I like about this submission is its simplicity and ease of use. The code is well-documented such that even a non-expert on the subject (such as me) can readily understand it and make changes as desired. It has a handy option to view the pathway's evolution; with nothing but a simple plot command, Joseph provides us with some strangely addictive animation.

I applied the function to a real-world problem by collecting latitude and longitude values for major US and Canadian cities off the web. I converted the HTML table into an Excel file, imported the data to MATLAB, and used the resultant vector as my input to the Traveling Salesman function. In order to see my results on a map, I added an extra line of code from the Mapping Toolbox:
geoshow( 'landareas.shp', 'FaceColor', 'LineWidth',2);
I inserted this line outside the main loop, which required some manipulation of the inner loop, but geoshow is the key command to get the map displayed. In the end, this was the fruit of my labor:

Traveling Salesman Animation

The proposed best route is as follows (different map projection for easier viewing):

Traveling Salesman Solution for Major US and Canadian Cities

Comments
Let us know what you think here or leave a comment for Joseph.

October 7th, 2011

Box plot + Scatter plot

Jiro's pick this week is notBoxPlot by Rob Campbell.

If you have ever used boxplot from the Statistics Toolbox, you know the value of being able to visualize statistical information on a plot.

pts1 = randn(20, 5);
pts2 = randn(10, 40);

figure;
subplot(2, 1, 1);
boxplot(pts1);
subplot(2, 1, 2);
boxplot(pts2, 'plotstyle', 'compact');

While box plots give the statistical information, you may also want the additional insight that you get from the raw data points. You can do that by holding the graph and plotting the data. Or you can just use Rob's function, which overlays the original data in a clever way, with some jitter to better distinguish the points.

figure;
subplot(2, 1, 1)
notBoxPlot(pts1);
subplot(2, 1, 2)
h = notBoxPlot(pts2);
d = [h.data];
set(d(1:4:end), 'markerfacecolor', [0.4,1,0.4], 'color', [0,0.4,0]);
set(d, 'markersize', 3);

There are quite a few entries on File Exchange that are related to boxplots, but I was quite intrigued by Rob's way of visualizing the data points. I like how he extended an existing functionality in the toolbox to create his reusable function. His function has a well-written help text with many examples, and I appreciate the healthy discussions he has on the entry page with some of the users of his function.

Comments

Give it a try and let us know what you think here or leave a comment for Rob.


Get the MATLAB code

Published with MATLAB® 7.13

September 30th, 2011

Determine File Dependencies

Brett's Pick this week is "FDEP: a pedestrian function dependencies finder," by Us.

Back in September, 2009, I featured a file called exportToZip that facilitates easy creation of Zip files. I'm still a fan of Malcolm's submission; I use it frequently.

Today's Pick facilitates the same functionality, plus more. FDEP "dissects [MATLAB] files and iteratively looks for all user-defined functions used during runtime." With a simple syntax:

fd = fdep('MorphTool.m')

you get a structure that shows a wealth of useful information. If you really want to dig in and detect all file dependencies for you MATLAB function, function DEPFUN does a pretty good job--but can be very slow. Us's file is a wrapper around DEPFUN, but "due to an efficient pruning engine," it can be much faster.

Output from depfun is a structure that includes information about Toolbox dependencies, function calls, help, subfunctions, and more. To create a complete zip file, for example, one could say simply:

zip('myZip',fd.fun);

Us's code is, as usual, difficult (for me, at least) to read, but superbly implemented and robust--I've learned to trust it over the years.

As always, comments to this blog post are welcome. Or leave a comment for Us here.


Get the MATLAB code

Published with MATLAB® 7.13

September 23rd, 2011

Import Test Cases From Excel Into Simulink

Greg's pick this week is CMTDTOOL by Yasumitsu Ito.

Contents

Adding Test Cases for Your Simulink Model a Pain? Check out the CMTDTOOL

While the Signal Builder block provides a convenient way to store a variety of test cases for a particular model, it’s less convenient to create and document the tests with it.

Test vectors are nice to store in some tabular form, at which Excel….errr excels. But it’s a little tricky to try and apply those nice tables of data to a Simulink model for testing. Just highlight the test cases in Excel and the click the "Excel Selection to Signal Builder" button and CMTDTOOL will import test vectors from Excel into a Signal Builder block.

This is something Simulink already provides an example for in MathWorks documentation but the CMTDTOOL wraps a nice GUI around this functionality. Now you can execute your nicely formatted test cases against your model of your design.

Test Cases for Designs in Simulink?….Booooriiiing!

Not many engineers enjoy discussing the testing of their designs. Compared to designing and making stuff, testing seems tedious and uncomfortable. It’s similar to going to the local department of motor vehicles to get your driver’s license renewed: it has to be done, but it involves a lot of waiting around with no comfortable place to sit.

Testing is the essence of simulation. The whole reason we simulate is to test out ideas quickly with little risk. And developing better tests helps you produce better designs. We engineers just don’t enjoy making it a formal process with lots documentation.

So It’s Easy, But What Else?

Personally I think it is useful because it allows me to define test cases in a natural format and quickly apply them to my Simulink model.

CMTDTOOL is also well documented. Once you execute the set-up script, the documentation is available in the MATLAB Help Browser.

So CMTDTOOL Brings Life and Vitality to Test Case Development?

Okay, that might be a little strong. A rose is still a rose no matter what name you give it. But certainly the CMTDTOOL can make the process of applying documented test cases to Simulink models less tedious and time consuming.

What Else Can CMTDTOOL Do For Me?

Import Truth Tables from Excel As the name implies, truth tables are tabular data that describe a set of actions based on a particular set of conditions. Again we see the theme of importing tabular data from Excel.

So this

becomes

Generate Model Test Harnesses In more rigorous development environments it is not desirable to change the design specification for testing. That means, “Don’t add stuff to the model just to test it!” The test harness generation will create a new model that references the model under test. The application of the input data and analysis of the system output data is done in the new model.

Generate a Report (i.e. “Show Me the $$”) In high integrity development processes, you haven’t done any testing until you have documentation that shows the results. The CMTDTOOL provides a nice mechanism for some basic reporting on tests of Simulink designs and comparison of expected results versus results from the Simulink simulation.

When engineers use Simulink to develop software specifications for flight code in airplanes, they need to demonstrate immense amounts of documentation that prove the designs have been tested. Automating the generation of the documentation certainly makes the development process easier.

Comments

If you would like to leave any comments regarding this post, please click here.

Or you can leave a comment for Yasumitsu Ito here.


Get the MATLAB code

Published with MATLAB® 7.13


MathWorks

Brett & Jiro share their favorite user-contributed submissions from the File Exchange.

These postings are the author's and don't necessarily represent the opinions of The MathWorks.