File Exchange Pick of the Week

Our best user submissions

Units Conversion Toolbox 2

Posted by Brett Shoelson,

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


Comments are closed.

2 CommentsOldest to Newest

Eric replied on : 1 of 2

I had a similar class called Units until the Mathworks hijacked this keyword with an invisible built-in class in R2011b. I had to rename my class and am still fixing code 6 months later. So if you’re writing OO code try to pick class names that you think nobody at the Mathworks will ever want to use.