File Exchange Pick of the Week

December 30th, 2011

Automatically add copyright information to your MATLAB files

Jiro's pick this week is addcopyright by Mirko Hrovat.

As a customer-facing engineer at MathWorks, I distribute a lot of MATLAB example files, including files posted on the File Exchange. As a policy, we add copyright information to our MATLAB files. I spend some non-trivial amount of time opening files and adding the copyright information to all of my files just before distribution. Little did I know that Mirko had created a nice utility for helping me with the process! He took the original entry by Raymond, one of my colleagues, and made some improvements to it.

The function adds a copyright text in the following format:

 %   Copyright 2011 The MathWorks, Inc.

One of lesser known features of a copyright string like the one above is that when you publish a file with this comment, it adds a footnote at the bottom with the copyright information:

The function is easy to use. To add a copyright line to all MATLAB files under "C:myDemos", simply type:

addcopyright C:myDemos

or you can apply this to individual files:

addcopyright myFcn.m

The function has many other options, such as customizing the organization name and the copyright year. Mirko describes in detail the modifications to Raymond's entry, but here are some of the ones I like:

  • Copyright line is added either before $Revision keyword or after a blank line. MATLAB files shipped with the product all contain revision information (edit any MATLAB function). But most of my files don't have a "$Revision" line, so I like the fact that it looks for a blank line.
  • Ability to have multiple copyrights with different organizations. If the file already contains a copyright, calling the function with a different organization name appends a new copyright line. This is useful when I am updating a file written by someone else from a different organization.
  • Automatic update of multi-year copyrights. If the file already contains "Copyright 2009", then calling it again with 2011 will change it to "Copyright 2009-2011".
  • Support for command syntax. Command syntax is useful when appropriate, and I think it's quite appropriate here. My examples above use command syntax. Compare this with the function syntax: addcopyright('myFcn.m')
  • Ability to remove copyright line. It's always nice to be able to undo the process.
  • Ability to add copyright to a single file (as opposed to all files inside folders). Sometimes, I just want to update a single file within a folder, so this is quite useful for me.

Thanks Mirko for this useful entry!

Comments

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

Oh, and I wish everyone a great new upcoming year!

Copyright 2011 The MathWorks, Inc.
Get the MATLAB code

Published with MATLAB® 7.13

December 23rd, 2011

Get Information About Your Computer

Brett's Pick this week is CPU Info by Ben Tordoff.

Today's is a quick-Pick, to go with our holiday greetings.

Occasionally, you might want to know some hard-to-find information about your computer. You could spend some time digging around in your documentation, or you could simply download and run Ben's CPU Info file. More important than just the information that Ben has elected to write out is that you can readily modify his code to extract all kinds of additional information. Unmodified, his function returns information like this:

myComputerInfo = cpuinfo
myComputerInfo.Name
myComputerInfo = 
             Name: [1x40 char]
            Clock: '2701 MHz'
            Cache: '256 KB'
    NumProcessors: 2
           OSType: 'Windows'
        OSVersion: [1x30 char]
ans =
Intel(R) Core(TM) i7-2620M CPU @ 2.70GHz

It doesn't get easier than that!

Thanks, Ben, and Happy Holidays, everyone! Looking forward to a great 2012!

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


Get the MATLAB code

Published with MATLAB® 7.13

December 16th, 2011

Simulink for Natural Interaction Device

Doug's pick this week is Simulink for Natural Interaction Device by Takashi Chikamasa.

Although I work at a software company my background is in mechanical engineering, so I'm a sucker for hardware. You might have seen the work I did to link Simulink with the Arduino platform. Needless to say, I was pretty excited when I saw Takashi, my colleague in our Japanese office, demonstrate this submission which allows you to connect a natural interaction device (NID) like Microsoft's Kinect or ASUS's X-tion Pro to Simulink. He has built a library of Simulink blocks that let you pull in data from an NID plugged into your computer's USB port. The interface is built on OpenNI's existing library, but allows you to leverage Simulink and other products like the Computer Vision System Toolbox to quickly build some advanced algorithms to interperet your gestures or motion.

Unfortunately I don't have an NID (yet) so I haven't been able to try it out myself, but I have seen it demonstrated and was impressed with what could be done. The submission includes a library of basic blocks that allow you to acquire video, depth map, infrared data, motion information, and the location of joints in a skeleton:

The submission also includes a couple of example models so you can get up and running quickly (click to enlarge):

Comments

If you get a chance to try it out, let me know here or leave a comment for Takashi.

December 9th, 2011

A Vivid Colormap

Jiro's pick this week is Vivid Colormap by Joseph Kirk.

Good uses of colors can help convey ideas effectively. It can help you accentuate certain concepts. Or you may need to use a gradient color that translates well when printed in gray scale. Joseph's entry really caught my attention. As the name suggests, it produces quite a vivid colormap. The idea is ingenious; he creates a gradient within each color, and that produces an accent at each level.

Let's see how it works. We'll first create a blue and red diverging color map, which gradually changes from blue to red with white in the center. We'll use the peaks function as the sample image.

% Create 13-level blue/red diverging color map:
level = 13; n = ceil(level/2);
cmap1 = [linspace(1, 1, n); linspace(0, 1, n); linspace(0, 1, n)]';
cmap2 = [linspace(1, 0, n); linspace(1, 0, n); linspace(1, 1, n)]';
cmap = [cmap1; cmap2(2:end, :)];

imagesc(peaks(500));
colormap(vivid(cmap)); caxis([-8 8]);
colorbar

Notice how vivid it looks! vivid also has additional options to change the level of gradients.

Less vivid:

colormap(vivid(cmap, [.4, .6]));

More vivid:

colormap(vivid(cmap, [0, 1]));

You can also get the regular colormap behavior:

colormap(vivid(cmap, [.5 .5]));

More on Colormaps

As I was writing this post, I learned quite a bit about colormaps. MATLAB has a set of standard colormaps described here. There are a few File Exchange entries that create additional colormaps, such as cbrewer, othercolor, and Color Palette Tables. There are also colormaps that would look nice when printed on a grayscale printer - Lab color scale and colorGray.

I also found a couple of entries that would have helped me with creating the blue/red diverging colormap - bluewhitered and makeColorMap.

Comments

Check out all the File Exchange entries on colormaps! If you have your favorite colormap, let us know here or try Joseph's vivid and leave a comment for him.


Get the MATLAB code

Published with MATLAB® 7.13

December 2nd, 2011

Will my flow be turbulent?

Brett's Pick this week is Moody, by Tom Davis.

I am not a mechanical engineer, though I did study fluid mechanics in my biomedical engineering past. In fluid flows, the Reynolds number is a dimensionless parameter that describes the ratio of inertial to viscous forces. This relationship is significant because, among other things, it can be used to predict the nature of the flow--whether laminar or turbulent. In biomechanics, fully developed fluid flows are typically of low Reynolds numbers, certainly below the critical threshold at which flow becomes turbulent.

However, in classical mechanics and hydraulics, flows are typically through long, often rigid, pipes. Flows become "fully developed," and can be of much higher Reynolds numbers. In these regimes, assuming one knows the characteristics of the pipe, one can calculate the Darcy friction factor to determine the (pressure) head loss during flow.

Okay, geeking out a bit. The relevance here is that the interplay of Reynolds numbers and Darcy factors can be difficult to deal with; Moody diagrams allow us to relate the two graphically, and to see at a glance whether, given a Darcy Factor and a Reynolds number, flow will be laminar or turbulent for pipes of a specified roughness.

Creating a Moody diagram is no trivial task, though. Or at least, it wasn't until Tom shared his MATLAB code for creating one. Function 'Moody' allows you to specify units (SI or Imperial) and paper size (A4 or Letter), and the name of an output file, and it will create a beautiful Moody diagram for you!

Thanks for sharing that, Tom! As always, comments to this blog post are welcome. Or leave a comment for Tom here.


Get the MATLAB code

Published with MATLAB® 7.13

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


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.