# File Exchange Pick of the Week

## May 17th, 2013

Jiro's pick this week is GPUBench by Ben Tordoff.

Some of you may know of the bench function. It allows you to benchmark your MATLAB on your machine and compare it against other machines. It performs some mathematical computation tests, as well as graphics tests. Note, as mentioned in the documentation, that bench is for comparing a particular version of MATLAB on different machines, not comparing different versions of MATLAB on a single machine.

GPUBench is GPU version of bench. With Parallel Computing Toolbox, you can perform MATLAB computations on NVIDIA CUDA GPUs with Compute Capability of 1.3 or greater. But your mileage may vary depending on the hardware you have. Sometimes, looking at just the Compute Capability may not be enough to see if one card is better than another for MATLAB computations. GPUBench will test your card and compare with other common GPU cards. Here's a sample table that gets generated from the benchmark. It reports in gigaFLOPS, so higher the number, the better the performance.

When I bought a MacBookPro last year and noticed that it had a supported GPU card, I ran the benchmark on it and got the following result. Note that this was done with an older version, so the list of cards is a bit old.

The "Host PC" refers to the CPU on my Mac, and "GeForce GT 650M" is the GPU that's equipped. We can see that the GPU seems to outperform the CPU on single-precision computations but not so much on double-precision computations.

Ben periodically updates the data files to include the newer GPU models that have come out. As of the writing of this post, the version includes benchmark data for K20.

Do you use GPUs, or are you interested in using GPUs for your work? Let us know about it here. If you do GPU computing in MATLAB, give this App a try and leave a comment for Ben.

Get the MATLAB code

Published with MATLAB® R2013a

## Colorspaces out the Wazoo!

Brett's Pick this week is "Colorspace Transformations", by Pascal Getreuer.

For inspiration for this week's Pick, I went back to my post from April of last year, in which I asked readers to suggest files to feature. I started to write up Pascal's submission long ago, but somehow got sidetracked, and I wanted to circle back around to it.

File Exchange champ Oliver Woodford casually suggested "a couple of useful ones." (His other selection was featured last August by Jiro.) Both of his "Picks" are quite useful.

So, what's so great about this colorspace converter? In particular, I really like the fact that Pascal's code extends the colorspace conversion capabilities beyond those offered by the Image Processing Toolbox, and that Pascal has included C-code (and instructions for calling it via the MEX interface) to make them faster.

Colorspace Transformations facilitates conversion to any of these colorspaces:

'RGB'              sRGB IEC 61966-2-1
'YCbCr'            Luma + Chroma ("digitized" version of Y'PbPr)
'JPEG-YCbCr'       Luma + Chroma space used in JFIF JPEG
'YDbDr'            SECAM Y'DbDr Luma + Chroma
'YPbPr'            Luma (ITU-R BT.601) + Chroma
'YUV'              NTSC PAL Y'UV Luma + Chroma
'YIQ'              NTSC Y'IQ Luma + Chroma
'HSV' or 'HSB'     Hue Saturation Value/Brightness
'HSL' or 'HLS'     Hue Saturation Luminance
'HSI'              Hue Saturation Intensity
'XYZ'              CIE 1931 XYZ
'Lab'              CIE 1976 L*a*b* (CIELAB)
'Luv'              CIE L*u*v* (CIELUV)
'LCH'              CIE L*C*H* (CIELCH)
'CAT02 LMS'        CIE CAT02 LMS

That's a lot of different ways to represent a color image!

Whenever I am asked to segment a color image--and trust me, that's pretty often!--my initial thought is to look at the R,G, and B colorplanes individually to understand where the information I'm after lies. I do this so often that I wrote and shared a utility that facilitates this exploration process. (In "Advanced Mode," ExploreRGB shows--in addition to RGB [and R, G, and B]--HSV, YCbCr, and L*a*b* versions of the image. I can often find a single-plane version of the original image in one of these transformed colorspaces that makes the segmentation easy. For instance, if I needed to isolate the central yellow pepper in the "peppers.png" image that ships with the Image Processing Toolbox:

I might consider (ironically) starting from the blue chrominance image (i.e., the second colorplane of the YCbCr representation of the image):

Starting with that image plane:

mask = ~im2bw(img,0.24);
stats = regionprops(cc,'Area');
A = [stats.Area];
[~,biggest] = max(A);
imshow('peppers.png')


Working in a non-standard colorspace made this segmentation problem easier than it might otherwise have been, and certainly easier than doing it in RGB-space would be.

(showMaskAsOverlay is a utility I shared for overlaying a transparent mask on an image.)

Okay, so back to Pascal's file.

With a little bit of code, I can use "Colorspace Transforms" to examine quickly many additional representations of the original image:

cs = {'RGB','YCbCr','JPEG-YCbCr','YDbDr','YPbPr','YUV',...
'YIQ','HSV','HSL','HSI',...
'XYZ','Lab','Luv','LCH','CAT02 LMS'};
figure('color','w');
ax = tight_subplot(numel(cs),4);
ind = 1;
for ii = 1:numel(cs)
newim = colorspace(['->' cs{ii}],peppers);
if max(newim(:)) > 1
newim = newim/max(newim(:));
end
axes(ax(ind));
imshow(newim,[]);title(cs{ii});
for jj = 1:3
ind = ind+1;
axes(ax(ind));
imshow(newim(:,:,jj),[]);title(sprintf('%s(:,:,%i)',cs{ii},jj));
end
ind = ind+1;
end
expandAxes(ax)


(tight_subplot was a previous Pick-of-the-Week.)

Now I have a lot more options at my disposal for segmenting images!

P.S. I know you can't really see what's happening in those tiny thumbnails*, but then that's the beauty of expandAxes; if you were to run the code snippet above, you would be able to click on any of those tiny axes and expand them to full-frame. And you could right-click on any expanded axes to export the image to the Workspace!

*P.P.S. If your image is large, doing what I just did could be a very bad idea. These aren't really "thumbnails"; even if the visualization is small, each of those image objects has in its "cdata" container a full copy of the image it reflects.

Thank you, Oliver, for the suggestion. And thank you, Pascal, for the very useful submission. Swag on the way to both of you!

As always, I welcome your thoughts and comments. Or leave feedback for Pascal here.

Get the MATLAB code

Published with MATLAB® R2013a

## Raspberry Pi DC Motor Driver

Doug's pick this week is Raspberry Pi DC Motor H-Bridge Driver Block by Joshua Hurst.

As my previous posts may suggest, I've been a long-time fan of the Arduino platform. Among other things I use it as the basis of a demonstration to showcase a variety of MathWorks' tools that includes driving a motor to rotate a camera to track an object. The Arduino works great for doing closed-loop position control of the camera, but falls short when it comes to actually processing the camera video to detect the object. So currently the video processing is relegated to my laptop which prevents me from creating a completely embedded solution.

Enter R2013a which introduced support for a number of new target platforms which Jiro pointed out earlier this year. I was drawn to Raspberry Pi in particular because it is a similar price and form factor to the Arduino, but has built-in support for USB webcams:

Looking at the blocks that are included with the target, however, you'll notice that there is nothing included for sending voltages to a DC Motor like you can do with the Arduino PWM Output blocks. Because of that I had initially planned to use both the Raspberry Pi and Arduino for my demo until I ran across Joshua's submission the other day. His model uses S-Function Builder blocks to take advantage of the new WiringPi support in the Raspberry Pi image that is used in the support package. Here's the top-level of Joshua's model:

After some breadboard work, I built and downloaded the model and I was controlling my motor in minutes by simply changing the Input Volts value in External Mode. Now I just need to decide on the best way to read the motor's potentiometer then the whole system can run on the Pi. Or perhaps I should bite the bullet and switch to an encoder. If anyone has any suggestions, leave a comment!

I was happy to see that Joshua was inspired by Giampiero's Device Driver guide that explains how to create custom drivers for the hardware support packages. Joshua has also recently uploaded several other related submissions. I'm looking forward to seeing what Joshua and others come up with in the future to increase the I/O options for the different hardware platforms.

One minor suggestion I would have for Joshua is to include the pin numbers that correspond to the PWM outputs for this model. I had to do a bit of hunting to track that down (it's 7 and 11 on the P1 header for those that are interested). But other than that, this submission has been a big help, thanks Joshua!

## Toggle that Fig

Jiro's pick this week is togglefig by our own Brett Shoelson.

Brett and I, along with Bob, started writing for this blog about 5 years ago, back when Doug was still the owner of the blog. Since the beginning, we typically highlighted submissions that were written by the general public and not by one of us. But ultimately, we like to highlight files that can be of some value to our readers, and I must say that there's no shortage of such files in Brett's entries.

So what does togglefig do? Have you ever wanted to better manage your figure windows? I've often had a need to reuse my figure windows. Once, I was developing some piece of code that created multiple figures, and as I was iterating on my code, I kept creating the same number of windows each time, and I would end up with tens of figure windows open after a while. Of course I could "close all" of them at the beginning of my script, but I had some windows I needed open for other reasons. As a solution, I would create/select figures using some numbers, e.g.

figure(123)


This would always use the same figure window, or create one if it doesn't exist. But I would want to give a meaningful name to it, so then I would need to set the name property after getting the handle to the figure.

h = figure(123);
set(h, 'Name', 'Important Window');


It works, but it's just some extra lines of code that are not adding any value to the real purpose of my program.

Brett's togglefig addresses this in a very elegant manner. It would raise the figure with the specified name, or create one if it doesn't exist.

togglefig('More Important Window')


You can also pass in an optional argument to clear the figure window when it's given focus.

Thanks, Brett, for this extremely useful function that makes me more efficient in using MATLAB!

Get the MATLAB code

Published with MATLAB® R2013a

## Manage the (Automatic) Naming of Your Figure Windows

Brett's Pick this week is "setname", by Andrew Bliss.

Some of you may be familiar with my own togglefig function; it allows one to recall and reuse a figure by specifying its name. I find it extremely practical, and I use it almost on a daily basis. (It's particularly useful when you're iterating on a block of code separated into "sections." Andrew's setname makes a very nice companion to togglefig.)

As of this writing, Andrew has 10 files on the Exchange, which have collectively been downloaded more than 500 times in the past 30 days. (Not too shabby!) Nonetheless, I don't believe any of his submissions have previously been recognized as a Pick of the Week. Until now.

Ironically, the file of Andrew's that I am most enamored of is his least-downloaded.

So what does Andrew's function do? If you've previously indicated a title for the axes in your figure, setname automatically renames the figure to match axes name. If you haven't titled your graphic, the function extracts a string from the x- and y- labels of the axes to construct a figure name.

Consider, for example, this snippet of code:

t = 0:pi/64:8*pi;
plot(t,sin(t)+rand(size(t)))
xlabel('Time')
ylabel('Noisy Sine')
title('Noisy Sinusoid')


This creates a figure not-so-usefully named "Untitled" (with a number appended to differentiate it from the other n "Untitled" figures you've previously created.)

Now issue the setname command (no arguments needed--it works by default on the current axes, though you may specify a non-default axes.) Now the figure is renamed to "Noisy Sinusoid," and you can readily pick it out from all the other open figures.

Alternatively, if you didn't explicitly provide a title, setname would automatically name the figure "Time vs Noisy Sine." Now not only can I find the figure, I can easily reuse it:

% Recall the previous figure...
togglefig('Noisy Sinusoid')
plot(t,cos(t)+rand(size(t)))
title('Noisy Cosine')
% ...and then rename the figure!
setname


This is brilliant, Andrew...thanks! One suggestion: it would be really nice if I could pass to setname an argument ('all'?) that tells the function to rename all open figures. (For those times when I've lazily created 20 different 'Untitled' figures.)

As always, I welcome your thoughts and comments. Or leave feedback for Andrew here.

Get the MATLAB code

Published with MATLAB® R2013a

## Simulate Robots with Sim.I.am

Jiro's pick this week is Sim.I.am by Jean-Pierre de la Croix.

This week, I had a trip to University of Cincinnati with my colleague (and fellow blogger) Sean de Wolski. There, I did a session titled "Enabling Project-Based Learning with MATLAB, Simulink, and Hardware". Project-based learning is a "collaborative education style facilitated by teachers, aimed at increasing students' retention of content in a way that is directly engaging, through projects applicable to life outside of the classroom." There are various tools that would serve the purpose of engaging students, and MATLAB and Simulink are certainly among them.

With MATLAB and Simulink, you can have software-based projects (simulations) and hardware-based projects. I wrote about some of the hardware support that is included with Simulink, and this allows you to easily take what you have in simulation onto low cost hardware. However, when you are trying to implement a project-based learning approach for a class of hundreds of students, purchasing hardware devices for every student becomes impractical. In that case, simulation becomes even more important.

Jean-Pierre is a Ph.D. student in GRITSLab at Georgia Tech (my alma mater!). Sim.I.am is a simulator that can be used to learn and apply control theory for mobile robots. The robot used in the simulator is based on the Khepera III (K3) mobile robot. This File Exchange submission comes with a detailed manual for the simulator, although the App is user-friendly and self-explanatory. What I like even more is the collection of programming exercises included with the package. It's ready to be used in a robotics course right away!

In this animation, you can see a target-seeking algorithm in action. The green dot indicates the target that the robot seeks.

At my session at University of Cincinnati, I also talked about a similar MATLAB-based Simulator for the iRobot® Create®. This simulator works alongside the MATLAB-iRobot Create interface, and this allows students to test their control algorithms they developed in simulation on the actual robot.

You can find other project-based learning materials created by people from around the world in the Classroom Resources page. Check out the Hardware for Project-Based Learning page to see what kind of hardware platforms interface with MATLAB and Simulink.

Get the MATLAB code

Published with MATLAB® R2013a

## 3D Image Viewer

Jiro's pick this week is Imagine by Christian Wuerslin.

This is just a cool app. It's a 3D image viewer with a well-designed user interface. I'm sure this will be useful to anyone working with slices of 3D images.

clear
whos

  Name      Size               Bytes  Class    Attributes

D         4-D               442368  uint8
S         4-D             21327411  uint8



Both "D" and "S" (pardon the nondescript names) are volumes of MRI data. "D" is from a data set that ships with MATLAB (load mri).

fprintf('Size of D:   %d x %d x %d x %d\n', size(D));

Size of D:   128 x 128 x 1 x 27


I created "S" from BrainWeb: Simulated Brain Database. They have simulated MRI data that people can use to test imaging techniques. I downloaded the "normal brain" data and the "MS lesion brain" data. I combined the two 3D MRI data, along with the difference between the two data sets, into a single variable "S".

fprintf('Size of S:   %d x %d x %d x %d\n', size(S));

Size of S:   181 x 217 x 181 x 3


Here's a peek at what this app can do. A few points to note:

• If you load in a 3D data set, you can scroll through the different slices using the scroll wheel on your mouse. You can also rotate to a different angle.
• The 4th dimension is displayed in different panels, and the data sets can be explored in sync.
• You can create custom analyses for a line profile or a polygon ROI. The tool comes with a default analysis routine, which you can see in the animation below.

He also includes a Users Manual that will get you up and running right away. Thanks for making an already easy-to-use tool even easier, Christian!

Get the MATLAB code

Published with MATLAB® R2013a

## Generate a Smile…Maybe

Brett's Pick this week is "Random Face Generator", by Joseph Hollmann.

I wrote today's post in advance. I fully expect that, when this goes live on Friday morning, I will be sitting on a tropical beach in the Dominican Republic, sipping umbrella drinks and contemplating the crystal clear cerulean water.

So, in the spirit of Spring Break and focusing on family fun, a bit of frivolity for today's Pick.

Joseph's submission doesn't really do anything of a practical nature, but it does make you smile. As he says in the preamble to his code, randomfacegenerator "generates a randomly created face and plots it....nothing else."

I have one suggestion for improvement. Calling the figure command in the function is probably unnecessary; you can easily end up with many open figures before you know it. I would suggest replacing the lines:

figure;
set(gcf,'name','Your New Face');

with a call to togglefig:

togglefig('Your New Face')

(That is, if a figure named "Your New Face" exists, activate and reuse it. Otherwise, create it.) No inputs required:

while ~strcmp(get(gcf,'currentcharacter'),'s')
randomfacegenerator
pause(0.5);
end

Thanks for putting me in vacation mode a day early, Joseph!

As always, I welcome your thoughts and comments. Or leave feedback for Joseph here.

Get the MATLAB code

Published with MATLAB® R2013a

## All Purpose Mortgage Calculator including mortgage schedule

Sean's pick this week is All Purpose Mortgage Calculator including mortgage schedule by S B.

I am currently in the fun process of buying a house. My wife and I were going over the mortgage calculations the other day and figuring out our approximate monthly payments and the amount of money we want to put down. We know that the financial company we are using probably knows how to do these calculations. But we wanted to check them! I also noticed that they were using Excel so that made me curious to see how easy this would be in my choice software for everything, MATLAB.

It's generally the case that if functionality for MATLAB seems obvious, it's probably built in to the product or one of the toolboxes. If this is not the case, then someone else has likely already written it and deposited it on the File Exchange. I vaguely remembered this App from a few months ago when my friend Doug and I were talking about the great low interests rates available right now.

NOTE All numbers below have been obfuscated to hide the actual financial details.

### Apps

In MATLAB R2012b, we introduced MATLAB Apps and the Apps Toolbar:

Using MATLAB Apps you can package your GUIs and their dependencies into single files that can be distributed and installed easily. This will help your users avoid the standard path issues. Apps also enable you to have easy version control and descriptions for your GUIs.

Side Note: I know that during the R2012b release many of you wanted to be able to change the App icon. In R2013a, the ability to select an icon from one of a dozen is available.

### This App

So let's take a look at this App:

We'll first try 20% down:

How does that compare to 5% down (not including Private Mortgage Insurance (PMI)):

So the total interest saved by putting down 20% instead of 5% is about \$28K, not including PMI.

What if we could shorten it to 15 years?

This just about halves the amount of interest!

Unfortunately, the plot does not work for any number of years less than 30 (enhancement!)

For every scenario, the numbers lined up with those that the financial firm gave us verifying both their calculations and this App.

### The Code

Though we have a big suite of Financial Products, none of them were used here. The engine behind this appears to be about 20 lines of MATLAB code and everything else is just for the GUI.

One thing I noticed is that S B did a lot of work for selecting the colors for the plot lines. Here's what he did:

color_map = ['rbgrbmbrgr'];
z1 = 0;
z2 = 0;

while (z1 == 0) | (z1 > 9) | (z2 == 0) | (z2 > 9)

z1 = fix(rand(1)*10);
z2 = fix(rand(1)*10);

% What are the chances of get the same random number twice!?
if (z1 == z2)
z1 = fix(rand(1)*10);
z2 = fix(rand(1)*10);
end
end
z1 = color_map(z1);
z2 = color_map(z2);

I would recommend just using randperm() to guarantee two unique integers between one and nine.

color_map = 'rgbcmyk';
idx       = randperm(numel(color_map),2);
color1    = color_map(idx(1))
color2    = color_map(idx(2))
color1 =

k

color2 =

b



### Some Suggested Future Enhancements

There are a few enhancements that would make this App even better!

1. The ability for it to plot for a term different than 30 years.
2. The ability to account for overpayments (e.g. by just changing the monthly amount).
3. The ability to account for PMI.

So the answer to my original question: How easy would it be to do this in MATLAB? Really easy!

Get the MATLAB code

Published with MATLAB® R2013a

## Additional Hardware Support in R2013a

Jiro's pick this week is a collection of new hardware support packages introduced in R2013a.

Some of you may know, especially if you've been reading some of the other blog posts, that we came out with our newest release of MATLAB R2013a last week. There are many new updates to various Toolboxes, so check out the Release Notes!

Since R2012a, we've been putting a lot of effort to make it easier for you to connect to different types of hardware, especially for use in academia. In R2012a, we added support for automatically running Simulink models on Lego® Mindstorm® NXT and BeagleBoard™. In R2012b, we extended the capability to Arduino® and PandaBoard™.

Now in R2013a, we have added support for Raspberry Pi and Gumstix Overo. In addition to these direct support within Simulink, the newest release contains support for Digilent Analog Discovery with Data Acquisition Toolbox, and support for Microsoft Kinect with Image Acquisition Toolbox.