File Exchange Pick of the Week

February 5th, 2010

Guitar Tuner

Today's Pick comes to us from guest Picker (pun intended) and MathWorks applications engineer Eric Johnson. When he's not playing with MATLAB, Eric can occasionally be seen roaming the floors at The MathWorks with his guitar in hand.

***************************

Do you play guitar and keep one near your computer for interim jamming? It's a fact of life that your guitar will need tuning from time to time. Tune it in MATLAB using Ryan's Guitar Tuner tool!

I like Guitar Tuner's clean, simple interface. When the note is within 10 cents (0.6% of the correct frequency) the tuner line lights up green. All of the code is contained in a single GUIDE-created MATLAB file so it can be easily customized. For instance, we can modify these lines:

    %CHECK IF TUNED WITHIN 10 CENTITONE:
    flat  = 15.43379*exp(0.05776234*(tone-0.1));
    sharp = 15.43379*exp(0.05776234*(tone+0.1));

to change the sensitivity to +/- 20 cents:

    %CHECK IF TUNED WITHIN 20 CENTITONE:
    flat  = 15.43379*exp(0.05776234*(tone-0.2));
    sharp = 15.43379*exp(0.05776234*(tone+0.2));

It also has a built in tone generator for tuning by ear. On a related note (pun intended) if you are using MATLAB for music-related applications you might also be interested in Musical Notes. Musical Notes is a collection of functions for converting between scientific pitch notation (A#4, E5, etc.), frequency, semitone/interval, and cents.

Comments?


Get the MATLAB code

Published with MATLAB® 7.9

January 29th, 2010

Patching together a BMW Z4

Contents

One From the Gallery

This week's Pick is of the Week is Car, by Ronald Biro.

Ronald's file creates a graphical reconstruction of a BMW Roadster, and gets me as close to this sweet ride as I am likely to get in the near future.

Ronald created his version of the Z4, shown here

using nearly 200 calls to his own version of "patches". Actually, Ronald's mypatch calls to and creates low-level surface objects. I'd be interested to hear the author's rationale for using surface objects instead of true patches. (For a brief discussion of the differences, read this.)

Just for comparison, here's the real deal:

Some Notes

When I first ran the Z4.m file, it executed perfectly on my computer. On the other hand, Bob quickly got an error running the same file on his computer. Why the difference? I like to disable warnings in my startup file, so the offending issue was ignored when I ran the code. In this case, had I enabled my warnings (their default state), MATLAB would have warned me me that "the variable "Z4" is also the name of this script." That can be problematic because MATLAB won't be able to differentiate the script from the variable in any context from which the script is called. (So, readers, be aware that you may need to suppress your warnings to run the file.)

One more thing: the integration of the M-Lint Code Analyzer into the MATLAB Editor is really helpful for identifying code issues. There are several places in which (more size-appropriate) preallocations might improve the performance of the code (admittedly, less of an issue in a just-for-fun gallery submission), and other places where command window output could be suppressed with a simple semicolon. Still, I like the file; a lot of work clearly went into it, and it is of limited practical use. My wife might say the same of me. :)

"Virtual Career Fair"

Also, before I sign off, one bit of promotion: The MathWorks will be holding a "Virtual Career Fair" from 11 a.m. to 7 p.m. on February 4, 2010. This Fair is designed to give graduate students and recent grads an opportunity to learn more about careers at The MathWorks, and to chat live with engineers and managers about the company. Interested? Register here.

Comments?


Get the MATLAB code

Published with MATLAB® 7.9

January 22nd, 2010

labelEdgeSubPlots

Bob's pick this week is labelEdgeSubPlots by Rob Campbell.

  • Do you use subplot a lot in your MATLAB analyses?
  • Do your subplots share the same X and Y range?
  • Do you like to label axes only along the left and bottom?

You could write code to do that yourself. It's not difficult.

for k=1:9
  ax(k) = subplot(3,3,k);
  plot(1:10)
  if mod(k,3)==1 %left
    ylabel Output
  end
  if k>6 %bottom
    xlabel Input
  end
end

Or you could just use labelEdgeSubPlots.

for k=1:9
  ax(k) = subplot(3,3,k);
  plot(1:10)
end
h = labelEdgeSubPlots('Input','Output')
h = 
    xlabels: [220.01 216.01 212.01]
    ylabels: [213.01 201.01 187.01]

Notice it returns axes handles. That helps customize your plots as much as you wish.

%make all axes labels italic
set([h.ylabels h.xlabels],'FontAngle','italic')

%draw special attention to center plot (12pt bold)
set([ax(5) h.xlabels(2) h.ylabels(2)],'FontWeight','bold','FontSize',12)

Another nifty feature involves how labelEdgeSubPlots handles sparse subplots as shown in Rob's example screen shot.

Comments?


Get the MATLAB code

Published with MATLAB® 7.9

January 15th, 2010

Fixing PostScript Lines

Jiro's pick this week is fix_lines by Oliver Woodford.

Have you ever generated PostScript files (such as EPS files) from your MATLAB graphs? I had to do that numerous times when I was in grad school and creating graphics for my publications. You can do extensive customization of your plot using basic plotting commands or handle graphics. I also wrote a guest blog post, "Making Pretty Graphs", on Loren's Blog.

Oliver's fix_lines comes into play at the final step. Let's say that we have the following graph. A lot of journal publications only accept black and white graphics. In that case, we have to make use of different line styles and thicknesses, instead of color.

x = 0:0.01:10;
y1 = sin(x);
y2 = cos(x);
y3 = sin(0.7*x) + 0.5*cos(1.3*x);
y4 = 1.5*sin(0.5*x) + 0.8*cos(0.9*x);
h = plot(x, y1, 'k-', x, y2, 'k:', x, y3, 'k-.', x, y4, 'k--');
set(h, 'LineWidth', 1.5);
legend('Data 1', 'Data 2', 'Data 3', 'Data 4', 'Location', 'Best');

We can create an EPS file.

print -deps2 -r600 fig1.eps

As we can seen below (left), the dotted and dash-dot lines need a little bit of tweaking. One way is to edit the EPS file using an external software. Or, you can use fix_lines.

fix_lines('fig1.eps', 'fig1_fixed.eps');

Notice that the lines look better after it's been "fixed" (right).

I love this because it allows me to do everything in MATLAB, from analysis to the final graph. Oliver's code is very well commented, so it's easy to follow what he's doing. Let us know what you think here.


Get the MATLAB code

Published with MATLAB® 7.9

January 8th, 2010

LUTBAR: A colormap tool to make your life easier

I don't know how many times I've spun my wheels, trying to determine the best colormap for a graphic I was working on, and cycling one-by-one through the built-in colormaps in MATLAB. MATLAB has many pre-defined colormaps, and selecting the best one can be a tedious process. At least, it was a tedious process. Us's LUTBAR tool streamlines the process by creating a toolbar of available colormaps; clicking on any entry automatically updates the figure's colorbar and allows you to see your figure in a variety of different colors. Better yet, LUTBAR automatically includes built-in colormaps, and enables you to include custom colormaps as well.

Let's say, for instance that you had this bit of code:

figure('color','w');
L = 40 * membrane(1,25);
x = -1:1/25:1;
s = surf(x,x',L,...
    'edgecolor','none',...
    'FaceLighting','phong', ...
    'AmbientStrength',0.3, ...
    'DiffuseStrength',0.6, ...
    'Clipping','off',...
    'BackFaceLighting','lit', ...
    'SpecularStrength',1.1, ...
    'SpecularColorReflectance',1, ...
    'SpecularExponent',7);
set(gca,'visible','off')
light('Position',[40 100 20], ...
    'Style','local', ...
    'Color',[0 0.8 0.8]);
light('Position',[.5 -1 .4], ...
    'Color',[0.8 0.8 0]);

Most of you will probably recognize the L-shaped membrane; it plays an interesting and important role at The MathWorks.(For the back story on our logo, check out Cleve's "History of MATLAB" video; it's just over 8 minutes, and well worth a watch!)

But you will also undoubtedly recognize that the coloring is "wrong." I could cycle manually (or even automatically) through the built-in colormaps:

mapOpts = {'autumn','bone','colorcube','cool',...
           'copper','flag','gray','hot','hsv',...
           'jet','lines','pink','prism','spring',...
           'summer','white','winter'};
for ii = 1:numel(mapOpts)
    set(gcf,'colormap',eval(mapOpts{ii}));
    pause(0.5);
end

Us gives us a cleaner, easier approach. All one has to do is issue the lutbar command:

lutbar

We now see a toolbar of selectable colormaps; clicking on any individual colormap icon updates the visualization. If you look with a careful eye, you might notice a separation line on the toolbar to the right of the (blue-to-green) 'winter' map. That line delimits the end of the built-in maps, and the beginning of a collection of user-defined maps. In fact, the last colormap on the toolbar is really just a uniform red colormap of my creation. Applying it yields the MathWorks logo we all know and love.

(Did you know that The MathWorks logo was uniformly colored, and that the apparent color gradations were created purely by manipulating the lighting?)

Us's code is beautifully implemented and documented; we've come to expect nothing less from him. Thanks for sharing this great function!

Comments?


Get the MATLAB code

Published with MATLAB® 7.10

January 1st, 2010

uiputfile2

Happy New Year!

  • Wow - 2010. It's a whole new decade.

Bob's pick this week is uiputfile2 by Chris Cannell.

This utility function is a wrapper to MATLAB's uiputfile command. What does it add? Memory. More specifically, it remembers the folder where the last file was saved. So when users of your GUIs want to save files, they don't have to navigate to their favorite folders every time. Nice.

Chris chose to implement uiputfile2 by simply saving the information (path to folder) in a MAT file. That way it remembers from MATLAB session to session. That strategy is also robust to upgrades. Sweet.

I know I could program the logic myself, but thanks to Chris I don't have to!

Comments?

See also (2010-01-05 update)

As Aurélien noted in addition to uiputfile2 Chris also posted uigetdir2 as well as uigetfile2. They also are similar location-persistent wrappers to uigetdir and uigetfile respectively.


Get the MATLAB code

Published with MATLAB® 7.10

December 25th, 2009

Input Dialog Box on Steroids

Jiro's pick this week is inputsdlg by Kesh.

This is pretty cool. There are quite a few different types of predefined dialog boxes within MATLAB. I use them quite often, and they serve my needs with the ability to customize them. But here comes the ultimate out-of-the-box dialog box utility. It combines all of the predefined ones into one and comes with a slew of customization capabilities.

The basic syntax is the same as inputdlg:

prompt = {'Enter the matrix size for x^2:';'Enter the colormap name:'};
name = 'Input for Peaks function';
answer = inputsdlg(prompt, name);

But then I can start going crazy with some of the customizations:

formats = struct('type', {}, 'style', {}, 'items', {}, ...
  'format', {}, 'limits', {}, 'size', {});
formats(1,1).type   = 'edit';
formats(1,1).format = 'integer';
formats(1,1).limits = [1 50];

formats(2,1).type   = 'list';
formats(2,1).style  = 'popupmenu';
formats(2,1).items  = {'jet', 'hsv', 'hot', 'cool', 'spring', 'summer', ...
  'autumn', 'winter', 'gray', 'bone', 'copper', 'pink', 'lines'};
defaultanswer = {20, 2};

[answer, canceled] = inputsdlg(prompt, name, formats, defaultanswer);

Here are a few things that I really like about this entry:

  • Extensive HELP. It follows a standard MATLAB file help structure seen in MathWorks files.
  • Data validation. It allows you to restrict data type and value ranges for each field.
  • Auto resizing. It allows auto resizing of the fields when you resize the dialog box.
  • Structure as output. Rather than getting the answers as a cell array, you can have it return the output as a structure with appropriate field names.

Here's an example that shows the full capability of this utility. Kesh includes the code that generates this dialog box. (click on the image to see it in full size).

Happy Holidays to all the MATLAB users out there! Thanks for reading our blog this year, and we'll see you all next year on New Year's Day!

Comments?


Get the MATLAB code

Published with MATLAB® 7.9

December 18th, 2009

Sparklines Table 1.0

Bob's pick this week is Sparklines Table 1.0 by James Houghton.

While I have not personally studied the methods of Edward Tufte* I have seen some interesting data visualizations over the years based on his work. I emailed a list of colleagues to see who might loan me his book to look up the reference James included in his submission (thanks for that). A common reply was "Which one? I have three" and it turned out the one James cited had two editions. So I am a little surprised there are not more Tufte plots on the File Exchange, but sparklines is a good start.

The basic idea with sparklines is to keep graphics as compact as possible. The combined plots and tabulated statistics are a neat idea. The fact that dozens of them can easily be seen together is an approach that I know will appeal to many.

James makes it clear in his description that this submission is a beginning. His code includes a list of "to do" items for future enhancement. I love the fact that he submitted early stage work. There is so much potential here. Collaboration might be just the ticket for getting more done faster.

*see also edwardtufte.com

Comments?


Get the MATLAB code

Published with MATLAB® 7.10

December 11th, 2009

The finest poker brains on your side!

I'm not a big fan of computer games (my own Yahtzee submission notwithstaning), but Luigi Giaccari's Poker Predictor reminds us that sometimes code can exist just for fun. (Perhaps those of you who actually earn a living playing Texas Hold 'Em can argue that poker is not "just for fun," but for our purposes here, let's assume that we all play cards just for the fun of it.)

Luigi's instructions for the installation and use of his tool are located at advancedmcode.org. Poker Predictor is a MATLAB tool to calculate poker game probabilities from any possible card configuration. Probabilities are computed with random card permutations; they are not exact, but are, according to Luigi, sure to be within 1% of the true values. The program can simulate 100,000 10-player Texas Hold 'Em games in a matters of 0.3 seconds, so it is actually a real time tool, very useful for online games--especially with high-level players. And Poker Predictor will allow you to specify your own cards, as well as those of your opponents.

Installing and setting up Luigi's file takes a bit of extra effort. You'll have to go to advancedmcode.com and download and install a fairly large (28+ MB) zip file of hand ranks. After that, it's easy; although his program uses a mex interface to C++ code, Luigi went so far as to include for you pre-compiled files for Win32!

Here's a snapshot of the tool, showing my probability of winning a 10-hand game with pocket aces, before the flop is turned:

I have a 31% chance of winning right from the get-go!

Now if you'll excuse me, I'm off to lighten the purses of my poker buddies, armed with some new knowledge...and my MATLAB-based odds calculator! :)

Comments?


Get the MATLAB code

Published with MATLAB® 7.9

December 4th, 2009

Back to Work with a Push and a Pop

Jiro's pick this week is pushd & popd by Peter Bodin.

Navigating through folders is a big part of my MATLAB workflow, especially because I may be working on multiple demos/projects at any one time. When I change folders, invariably I may want to come back to where I was.

Contents

Example

Here's an example illustrating my workflow. I'll use pushd and popd to help me do this.

I'm currently working on this blog post. I am located here:

pwd
ans =
C:\MyStuff\Work\NoCopy\Blog\POTW\PushPop

I just got a call from Bob and Brett saying that they need an updated version of the GUI Building demo ASAP. Time to switch folders!

% works like CD
pushd C:\MyStuff\Work\Demos2009b\GUIBuilding
pwd
ans =
C:\MyStuff\Work\Demos2009b\GUIBuilding

I realize that I am missing a couple of key files for this demo. Well, that's understandable. I haven't ported over the files from my master version. I'm not quite sure which files I need, so let me go check.

pushd ..\..\Demos_public\GUIBuilding
pwd
ans =
C:\MyStuff\Work\Demos_public\GUIBuilding

I find out that I need two files: "myFilter.m" and "myPSD.m". Let me capture this folder name.

copyFromFolder = pwd;

I go back to my R2009b demos folder and copy over the two files.

popd
pwd
copyfile(fullfile(copyFromFolder, 'myFilter.m'));
copyfile(fullfile(copyFromFolder, 'myPSD.m'));
ans =
C:\MyStuff\Work\Demos2009b\GUIBuilding

Now, I can zip this up and email it to Bob and Brett.

zip('GUIDemo.zip', ...
  {'filteringGUI.fig', 'filteringGUI.m', ...
  'myFilter.m', 'myPSD.m', 'myImportfile.m'});

% I'm commenting this part out so that it won't keep sending email to my
% buddies every time I publish this script.
%
%   sendmail({'Robert.Bemis@mathworks.com', 'Brett.Shoelson@mathworks.com'}, ...
%     'GUI Building Demo', 'Hi Bob and Brett, here it is!', 'GUIDemo.zip');

Now, I'm ready to get back to my blog post! Ta-dah!

popd
pwd
ans =
C:\MyStuff\Work\NoCopy\Blog\POTW\PushPop

In Addition...

Another nice feature of pushd is that you can pass in any file that is on the MATLAB path, and it will go to that directory. For example, I know that there is an AVI called "rhinos.avi", which is one of the demo files from the Image Processing Toolbox. I want to see the other demo files from that toolbox.

pushd rhinos.avi
pwd

% go back
popd
ans =
C:\Program Files\MATLAB\R2009b\toolbox\images\imdemos

Interactive Alternative

If you'd rather click your way through, we have that built-in to the Current Folder Browser.

Notice the Back and Forward buttons to "pop" back to where you were. Ken and Mike blogged about it here.

Comments

These types of tools help users in the development phase. They may never show up in the end product, but since MATLAB is a development platform, these functions could drastically improve the MATLAB experience. Let me know of other File Exchange entries that fall into this category. I can already think of a couple.


Get the MATLAB code

Published with MATLAB® 7.9


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

  • Doug: Ben, The name is in the name field as you saw in the video: files(1).name will give you just the name of the...
  • Ben: Hey, Thank you for the tutorial but I must ask, once you have the files required in the array, how do you parse...
  • jiro: Nisa, I’m not familiar with the Psychtoolbox. It’s not a toolbox developed by the MathWorks. As far...
  • nisa: Hi, I have just started to learn to use mathlab can this myaa codes be used with mathlab 7.5.0(R2007b)using...
  • Doug: @Rupa, Could you do this algorithm and then remove the two points and run again? Not efficient, but could be...
  • Doug: From the convhull doc http://www.mathworks .com/access/helpdesk /help/techdoc/ref/co nvhull.html xx = -1:.05:1;...
  • Mark: Very nice function, indeed, thanks for that. But why does’t MATLAB freeze the colormaps for subplots...
  • Steve L: MAuricio, From the description it sounds like the features variable is a cell array that itself contains a...
  • Fred: Doug, I have a set of coordinates for the perimeter of an object in random order. I want to plot these using...
  • Rupa: Hi, sorry to digress but I have a similar problem, I think. I would like to find the three (or n) smallest...

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