1 ## Copyright (C) 2005 Carl Osterwisch <osterwischc@asme.org>
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
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
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/>.
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.
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:
31 ## units ("mile/hr", "m/sec", [30, 55, 75])
34 ## 13.411 24.587 33.528
38 function y = units(fromUnit, toUnit, x)
39 if 2 > nargin || 3 < nargin || !ischar(fromUnit) || !ischar(toUnit)
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.']);
47 i = index(rawoutput, "*");
48 j = index(rawoutput, "\n") - 1;
49 i && (i < j) || error('parsing units output "%s"', rawoutput);
51 exist("x", "var") || (x = 1);
52 eval(['y = x', rawoutput(i:j), ';'])
56 %! a.value = 100; a.unit = 'lb';
57 %! b.value = 50; b.unit = 'oz';
59 %! c.value = units(a.unit, c.unit, a.value) + units(b.unit, c.unit, b.value)
61 %!assert( units("in", "mm"), 25.4 )