Re: Extracting units from a list of values

*To*: mathgroup at smc.vnet.net*Subject*: [mg27420] Re: Extracting units from a list of values*From*: "Allan Hayes" <hay at haystack.demon.co.uk>*Date*: Sun, 25 Feb 2001 00:53:47 -0500 (EST)*References*: <9750ck$6ke@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

Thomas, {5, 2 Pi, 3 E Meter^2} /. {_?NumericQ:>1, _?NumericQ * unit_->unit} {1, 1, Meter^2} -- Allan --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay at haystack.demon.co.uk Voice: +44 (0)116 271 4198 Fax: +44 (0)870 164 0565 "Thomas Anderson" <tga at stanford.edu> wrote in message news:9750ck$6ke at smc.vnet.net... > As part of the package I'm working on, one of the functions takes > a list of measured values as an argument. For maximum flexibility, > I wish to accept either a list of dimensionless numbers or a list > of numbers with units, i.e. > > {1, 2, 3} > or > {1 Meter, 2 Meter, 3 Meter} > > for example. As part of the argument checking, I want to be able > to test whether the units are consistent: everything should either > be dimensionless or have the same units. > > The problem boils down to: how can I separate the units from the > numeric part of the value? I've tried a few things, and so far my > best attempt has been > > Replace[vals, (_?NumericQ unit_.) :> unit, 1] > > where vals is the list of values. This works pretty well: > dimensionless numbers give a list of "units" of 1, and values like > "2 Meter" or "1 Elephant^2" give "Meter" and "Elephant^2" respectively. > > This method doesn't work, however, with input containing more > complicated numerical values. For example, {1, 2 Pi, 3 E Meter^2} gets > transformed into {1, 2, 3 Meter^2}, whereas I want {1, 1, Meter^2} for > these values. I could apply N[] to the values before extracting the > units, but then "Meter^2" becomes "Meter^2.", which I don't want. > > This isn't a huge problem, since I'm expecting the values to be > integers > or real numbers, but I want my code to be as bulletproof as possible. > > Thanks in advance for any suggestions. > > -Tom Anderson > tga at stanford.edu > >