]> Creatis software - CreaPhase.git/blob - octave_packages/miscellaneous-1.1.0/units.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / miscellaneous-1.1.0 / units.m
1 ## Copyright (C) 2005 Carl Osterwisch <osterwischc@asme.org>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {} units (@var{fromUnit}, @var{toUnit})
18 ## @deftypefnx {Function File} {} units (@var{fromUnit}, @var{toUnit}, @var{x})
19 ## Return the conversion factor from @var{fromUnit} to @var{toUnit} measurements.
20 ##
21 ## This is an octave interface to the @strong{GNU Units} program which comes
22 ## with an annotated, extendable database defining over two thousand 
23 ## measurement units.  See @code{man units} or 
24 ## @url{http://www.gnu.org/software/units} for more information.
25 ## If the optional argument @var{x} is supplied, return that argument
26 ## multiplied by the conversion factor.  Nonlinear conversions
27 ## such as Fahrenheit to Celsius are not currently supported.  For example, to 
28 ## convert three values from miles per hour into meters per second:
29 ##
30 ## @example
31 ## units ("mile/hr", "m/sec", [30, 55, 75])
32 ## ans =
33 ##
34 ##   13.411  24.587  33.528
35 ## @end example
36 ## @end deftypefn
37
38 function y = units(fromUnit, toUnit, x)
39     if 2 > nargin || 3 < nargin || !ischar(fromUnit) || !ischar(toUnit)
40         print_usage;
41     endif
42
43     [status, rawoutput] = system(sprintf('units "%s" "%s"', fromUnit, toUnit), 1);
44     (0 == status) || error([rawoutput,
45         'Verify that GNU units is installed in the current path.']);
46     
47     i = index(rawoutput, "*");
48     j = index(rawoutput, "\n") - 1;
49     i && (i < j) || error('parsing units output "%s"', rawoutput);
50
51     exist("x", "var") || (x = 1);
52     eval(['y = x', rawoutput(i:j), ';'])
53 endfunction
54
55 %!demo
56 %! a.value = 100; a.unit = 'lb';
57 %! b.value =  50; b.unit = 'oz';
58 %! c.unit = 'kg';
59 %! c.value = units(a.unit, c.unit, a.value) + units(b.unit, c.unit, b.value)
60
61 %!assert( units("in", "mm"), 25.4 )