File Exchange Pick of the Week

February 3rd, 2012

Units Conversion Toolbox

Brett's Pick this week is Units Conversion Toolbox, by John McDermid.

Once, a long time ago, I was a real engineer, working on real engineering problems. My trusty HP 48S Scientific Calculator was always by my side when I was working, largely because of its capacity to manage my units. That is, I could readily add joules to BTUs without worrying about first converting to like units. (This occasionally annoyed my professors when I was a student; "my calculator did it for me was rarely well received." On the other hand, it gave me a [perhaps false] sense of security when my answer to an involved question came out in appropriate fundamental units.)

Time marches inevitably onward; I don't do a lot of hard engineering any more. Instead, I get to spend my days helping people solve problems in MATLAB. Occasionally, I still need to do some unit conversion and, until recently, those occasions typically have had me dusting off the old HP (which is still on my desk!). But I'm always pleased when I find new ways to stay in the MATLAB environment, and John's Unit Conversion Toolbox essentially consigns my calculator to the dustbin.

John has done a significant amount of work defining virtually every unit I can think of. It's quite easy to use, and includes impressive documentation--including a useful "Getting Started" doc. It also manages prefixes (like 'femto' and 'kilo') seamlessly. Now when I add joules to BTUs--and express the answer in either, or in fundamental units, or some different unit of energy--I can do it right from MATLAB!

x = unit(1,'milliBTU');
y = unit(2,'joule');
z = x + y
z2 = convert(z,'cal')
z3 = convert(z,'dyne')
 
z = 
     3.05506 m^2*kg/s^2
 
z2 = 
     0.729688 cal
Error using unit/convert (line 315)
Incompatible conversion! Fundamental units of m^2*kg/s^2 vs. m*kg/s^2
Error in unitconversion_potw (line 46)
z3 = convert(z,'dyne')

John implemented this impressive suite using MATLAB classes, MATLAB classes, and he took pains to ensure that arithmetic operations work as expected. And I'm encouraged that when I tried to do something foolish there, the unit class told me about it!

Very useful, John--thanks for sharing this!

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


Get the MATLAB code

Published with MATLAB® 7.14

January 27th, 2012

A non-engineer tinkers with Simulink

Greg's pick this week is A non-engineer tinkers with Simulink by Dimitri Shvorob.

Contents

Non-Engineer Using Simulink…Does Not Compute.

Although I don’t always understand our users' day-to-day jobs, I’m always interested to learn how they are applying MathWorks tools--especially for “non-traditional” applications.

And while I’m not sure finance will be the next major boom market for Simulink, I find Dimitri’s perspective on Simulink refreshing.

For example, in Dimitri’s models:

  • The units of time are years rather than seconds
  • Block names and titles describe the purpose of their operation
  • The models contain a plethora of additional documentation
  • While these are not the most sophisticated models you will ever see, they are clean and simple to follow. Which is more than I can say for many a model I have produced.

    Can the Rest of Us Learn to Label Blocks Too?

    I am certainly guilty of building a model quickly to describe some particular dynamic system, but then forgetting to go through and change my block names. All of a sudden I have 20 blocks all named “Subsystem”, and I forget why they are in the model and what they do. This is especially painful if I end up going back to the model after a couple of weeks.

    As someone who often needs to work with Simulink models built by other people, I don’t know that I can suggest strongly enough the value in spending the extra time to flesh out the model with details like block names, signal names, and occasionally, general comments as Simulink Annotations.

    On the other hand, it does speak to how powerful a tool Simulink can be, that we can construct a complex, sophisticated simulation without ever labeling a single block. (Although, I’m not sure I want to admit to that in print!)

    Comments

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

    Or you can leave a comment for Dimitri Shvorob here.


    Get the MATLAB code

    Published with MATLAB® 7.13

    January 20th, 2012

    Publishing called functions

    Jiro's pick this week is "Publish dependent and called functions" by Nick Angelini.

    Publishing is one of the things I always highlight to MATLAB users, new or experienced. Even though the feature has been around for over 7 years, not many people know about it. I was one of those people who went through graduate school manually creating reports from figures generated in MATLAB. Now, publishing is something that I can't live without. Even many of the bloggers (myself included) on MATLAB Central use publish to write the blog posts.

    I was pretty excited to see this entry by Nick. I've always wanted to make something like this, but I never got around to implementing it. While publish would only generate a report for the function or the script you specify, publishdepfun will generate separate reports for any user-defined functions used in the main file, and even append the report to the end of the main report. I immediately found one of my demos that I show at seminars and published it. The syntax is pretty much identical to the MATLAB's publish command. You can also pass in the options structure that's accepted by publish.

    publishdepfun('MainAnalysis');

    My MainAnalysis.m script had 3 custom functions: createFit.m, createfigure.m, and importfile.m. Those 3 functions were published as well and were appended to the end of the main report. As you can see below, the report has a section called "Called Functions".

    Comments

    He states in entry that there are still some limitations, but I think this is a great start and has plenty of good utility. Let us know what you think here or leave a comment for Nick.


    Get the MATLAB code

    Published with MATLAB® 7.13

    January 13th, 2012

    Drag Objects Conveniently

    Brett's Pick this week is Draggable, by Francois Bouffard.

    For a pet project of mine, I needed to implement (in MATLAB code, of course!) a repositionable, resizable rectangle. I wanted to be able to drag the rectangle itself, but I also wanted to expose "handles" that would allow me to drag from the sides or from the corners, and to control, or constrain, the motion.

    As a first step, I needed a general function that facilitated "draggability" of MATLAB objects. That's where "Draggable" comes in. Starting, as I usually do, with the File Exchange, I quickly found my way to Francois's file. I downloaded it, encouraged by several 5-star reviews (now including my own!), and was very pleased by how tractable the problem became.

    "Draggable" is exceptionally well implemented, and despite having taken it for a significant test drive, I have been unable to find fault with it.

    Francois mentioned in his comments that he plans to revisit his code at some point in the future to enable one to apply the functionality simultaneously to multiple handles. I agree that that would make a nice enhancement, though activating objects one-at-a-time wasn't extremely onerous. It would also be nice if there were a "diagonal" constraint--at least for my purposes. But in its current state, I'm very happy to select "Draggable" as this week's Pick of the Week--very nice work, Francois!

    Incidentally, my "draggableRect" isn't on the File Exchange yet, but I hope to have it up soon!

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


    Get the MATLAB code

    Published with MATLAB® 7.14

    January 6th, 2012

    Watch HDTV in MATLAB

    Idin's Pick this week is ATSC: From RF to Video, by Dick Benson.

    Watch HDTV in MATLAB? Well, not quite. This submission shows how to receive ATSC signals (standard used for HDTV in North America) using MATLAB/Simulink, but it’s not real-time. Nonetheless, this is one of the most complete examples of a communication system available on MATLAB Central as it contains every aspect of the receiver from RF to the final video stream. It shows how a standards document comes to life, following a top-down design approach (see the ReadMe file).

    The files in this submission show an ATSC receiver that can demodulate, decode, and display a captured off-the-air TV signal. The data file containing the captured signal is provided separately here (1.8 GB). The data file contains a 20-second signal from a weather broadcast on WCBV in the Boston area.

    The final model for processing captured signals is shown below:

    The raw captured data is passed through two other models to do timing/carrier synchronization and equalization before it is passed to this model. This model contains the symbol processing that follows all front-end processing (it does demodulation, decoding, and MPEG-2 file creation). The final result is an MPEG-2 video transport stream (.ts) file that can be played using Windows Media Player (or any other MPEG-2 player).

    The ReadMe file contains detailed description of the algorithms used in each model along with references. It serves as a nice tutorial for using Simulink as well as designing digital receivers (not just ATSC).

    Overall, this is a great submission that can be used as a guide in designing any digital receiver in Simulink. It covers every aspect of the problem from capturing off-the-air signals to synchronization and debugging of the models. For more basic tutorials and examples on using Simulink for communication system design, see the demos in the Communications System Toolbox (or the Communications Blockset in R2010b and older versions).

    Brief ATSC Standard Background

    ATSC standards for digital video transmission were developed in the 1990s by American Television Systems Committee. ATSC was adopted by the FCC in the US in mid-90s; however, the switch to digital did not occur until 2009. In June 2009, television broadcast in the US converted from analog NTSC to digital ATSC (more commonly referred to as “digital TV” or “HDTV”). Canada switched in August 2011, with Mexico to follow in 2015. ATSC uses 8-VSB modulation over the air, protected by Reed-Solomon error-correction coding. The video stream is encoded using MPEG-2 specifications, and Dolby Digital’s AC-3 audio codec is used for audio encoding.

    Let us know what you think, or leave a comment for Dick here!


    Get the MATLAB code

    Published with MATLAB® 7.14

    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


    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.