Code covered by the BSD License  

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
Units Conversion Toolbox

4.69231
4.7 | 14 ratings Rate this file 36 Downloads (last 30 days) File Size: 106 KB File ID: #29621 Version: 1.5

Units Conversion Toolbox

by

John McDermid (view profile)

 

04 Dec 2010 (Updated )

This toolbox attaches units to Matlab variables and enables unit conversion.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

Have you ever needed to convert horse power to watts but can't remember the conversion factor? How many inches light travels in a microsecond? This toolbox is designed to make getting these answers much easier.

The "unit" statement attaches units to a variable. For example,
>> x=unit(2,'yards')
 
x =
     1.8288 m

returns the answer in International (SI) units. If you would rather have you answer in feet it can be converted to feet by

>> convert(x,'feet')
 
ans =
     6 feet

Variables created by the "unit" statement can operated on by these operators:

      Unary plus, Unary minus, +,-,*,.*,/,\,./,.\,^,.^,',.'
      and sqrt

Variables are also supported by triginometric,hyperbolic, and exponential functions and can be compared by

       ==, ~=, >, <, >=, and <=

Special plotting routines are available for plotting variables with units. These are:

      plot, semilogx, semilogy, and loglog

The toolbox appears in the html help screens and has "GettingStarted', "User Guide", and function help screens.

Just down load the tool box to the directory of you choice and set the Matlab path to include this directory. To verify operation, type

>> unit('yards')
 
ans =
     0.9144 m

If you get this result, you are all set!

Acknowledgements

This file inspired Unit Converters.

MATLAB release MATLAB 7.11 (R2010b)
Other requirements none
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (22)
10 May 2016 Leandro Barajas

Very clean, useful, and expandable implementation.
Small issue with:
unit('Hz') = 6.28319 1/s
it should be unit('Hz') = 1 1/s
See: https://en.wikipedia.org/wiki/Hertz

convConstant.m needs to be updated to:

case {'hertz','Hz'} % frequency in hertz y=units2convFac(unit('1/second'));

Comment only
26 Apr 2016 Mark Mikofski

Mark Mikofski (view profile)

Try quantities.
http://www.mathworks.com/matlabcentral/fileexchange/48988-mikofski-quantities
Inspired by python Pint.

Comment only
31 Mar 2016 Fernando Freitas Alves

I would be much more useful if we could have the option to store a value in any unit instead of stacking with primitive units.
For example, instead of:

unit(1,'ft') = 0.3048 m

it would be better if the result was not automatically converted, like:

unit(1,'ft') = 1 ft

Anyway, your structure is very good. Congratulations!

03 Dec 2015 Erich

Erich (view profile)

Frederik,

Hz is converted to rad/s, because 'Hz' is the same as 'cycle/s' and a cycle is 2π radians. Since radians are unitless, the unit displays as '1/s'.

>> unit(2,'Hz')
ans =
12.5664 1/s
>> 2*2*pi
ans =
12.5663706143592
>> unit(2,'rad/s')
ans =
2 1/s
>> unit(2,'cycle/s')
ans =
12.5664 1/s

Comment only
03 Dec 2015 Frederik Vanhollebeke

Looks like an error?

>> unit(2,'Hz')

ans =
12.5664 1/s

24 Nov 2015 Florian Schwaiger

To be precise, this test case fails:

classdef UnitConversionTests < matlab.unittest.TestCase
methods (Test)
function convertMustNotEditOriginal(self)
feet = unit(3.3, 'ft');
meter = feet.convert('m');
feet2 = meter.convert('ft');

self.verifyEqual(feet.name, 'ft');
self.verifyEqual(meter.name, 'm');
self.assertEqual(feet2.name, 'ft');

self.verifyEqual(feet2.value, feet.value);
end
end
end

Comment only
23 Nov 2015 Florian Schwaiger

While this does work, a central part is misleading with bad code style:

% this example is obvious, convert changes the object
feet = unit('ft');
convert(feet, 'm');

% in this case, the feet object must not change, however, both feet and meter are identical then
feet = unit('ft');
meter = convert(feet, 'm');

06 Sep 2015 Kurt Feigl

GREAT JOB! I use this code every day (at work). However, I found out (the hard way) that the symbol "g" does not denote "gram".

Instead, it "g" is coded as the gravitational acceleration on Earth as
unit(1,'g') = 9.80665 m/s^2

To get units of mass, I use:
unit(1,'gram') = 0.001 kg

Error using unit/convert (line 315)
Incompatible conversion! Fundamental units of kg/m^3 vs. 1/m^2/s^2

This issue led to the error message below:

density = unit(1000,'kg/m^3')
convert(density,'g/cm^3')

Error using unit/convert (line 315)
Incompatible conversion! Fundamental units of kg/m^3 vs. 1/m^2/s^2

18 Aug 2014 Nick Dutton

Hi,

I noticed that the conversion from eV to Joules is incorrect.

Line 104 of convConstant.m should read:

"y=units2convFac(1.60217646e-19*unit('J'))"

Besides this one error, very nice utility!

05 Nov 2013 Sinan

Sinan (view profile)

There is an error using units with offset.

test = unit('C');
answer = 2*(test+test);

answer should give result of
1096.6 = 2*(274.15+274.15);

I implemented the following to avoid this error.

In classdef unit in function U=unit(varargin) ...
switch nargin
...
case 2
%find this line

if isa(varargin{1},'double') && isa(varargin{2},'char')
X=unit(varargin{2});
U=X;
if U.hasBeenConverted == false
U.value=varargin{1}*X.value+X.offset;
U.offset = 0;
else
U.value=varargin{1}*X.value;
end

I hope this does not interfer with other functionalities, but my verifications showed no strange behaviour anymore.

Many thanks for your tool!
Best regards
Sinan

24 Aug 2012 Matthew M.

I've been thinking about incorporating this for a while, hemming and hawing. Tried it today, finally, and I'm sold. Great job.

I wish there were a way to match the display to the Command Window format setting - I generally like to display more significant digits than short g allows. But it appears that there's no easy way to retrieve the current command window display format (I'll bet Yair Altman could figure one out, but I couldn't). I know you can use the .value method to display it in the desired format, but that's sort of inelegant.

The workaround for me was to edit unit\display directly, changing the sprintf format from %g to %0.12g (I chose 12 rather arbitrarily).

Thanks!

30 Apr 2012 Marco

Marco (view profile)

I cannot use this toolbox to find roots of polynomial using the roots function when coefficientes are unit-class type. I first have to define a isfinite function in the unit class, but then I have problems with the transpose and ctranspose function I am unable to solve myself. Can someone help?

Comment only
30 Apr 2012 Marco

Marco (view profile)

can you add this function to the unit class? Some formulas has absolute value in them, and I need to preserve units.

function C=abs(A)
A=unit(A);
C=A; C.value=abs(A.value);
end

02 Apr 2012 Ronan CIMADURE

Perfect :)

18 Jan 2012 Collin

Collin (view profile)

 
18 Jan 2012 Collin

Collin (view profile)

Great toolbox.

Ran into a small problem with non-dimensional unit's plus and minus (unit class with .name = ''). I fixed the problem by replacing all the

if A.name == B.name
......
end

with

if strcmpi(A.name,B.name)
......
end

as ''=='' is an empty matrix

21 Nov 2011 John

John (view profile)

Thanks Erich, that works perfectly

18 Nov 2011 Erich

Erich (view profile)

Try
>> a= unit([1 2],'m')

Comment only
17 Nov 2011 Michael Katz  
16 Nov 2011 John

John (view profile)

This is a great toolbox to have handy but it seems to have problems with vectors and arrays of objects. For example, (I am running MATLAB 2010b):

>> a = [unit(1,'m') unit(2,'m')]

a =
??? Error using ==> plus
Too many input arguments.

Error in ==> unit>unit.display at 1827
s=sprintf(' %g %s',x.value+x.offset,x.name);

But when I change it to

>> a = [unit(1,'m') unit(2,'m')];

there is not issue. It seems the call to sprintf is having trouble with multiple inputs.
Overall this printing issue is not what concerns me, it is when I try to perform an operation on this array when I really run into trouble:

>> a * unit(1,'m')
??? Comma separated list must have exactly one item.

Error in ==> unit>unit.unit at 163
if U.hasBeenConverted

Error in ==> unit>unit.mtimes at 387
A=unit(A);B=unit(B);

I was hoping to get back a <1x2 unit> where both values are now in m^2. I run some highly vectorized code and it was be great if this issue could be resolved, overall great toolbox. Thanks

Comment only
21 Sep 2011 Erich

Erich (view profile)

Very easy to work with units using this toolbox. Author quickly updated the files when R2011b introduced an incompatibility.

09 Sep 2011 Erich

Erich (view profile)

In MATLAB R2011b I get:

>> Units(3, 'ft')
Error using Units
Error: File: Units.m Line: 1 Column: 10
Naming a class 'Units' is not allowed, because it is already a built-in class.

Comment only
Updates
16 Sep 2011 1.1

This program has been updated to resolve a problem that appeared in R2011b.
R2011B used "Units" as a built in function in a toolbox and does not check to see if you have the toolbox before throwing an error. "Units" has been renamed to "unit".

21 Sep 2011 1.3

This update was submitted and approved but did not end up in Matlab Central. Instead, the old one was there.

21 Sep 2011 1.4

I made an omission on the last submission and no file (or the old file) was attached. This is the correct file!

25 Jan 2012 1.5

This update corrects the addition and subtraction of dimensionless quantities (previously reported an error) and also corrects the definition of a weber.

Contact us