Re: Replace non-numeric values in a list
- To: mathgroup at smc.vnet.net
- Subject: [mg88767] Re: Replace non-numeric values in a list
- From: dr DanW <dmaxwarren at gmail.com>
- Date: Fri, 16 May 2008 05:30:44 -0400 (EDT)
- References: <g0h825$mtr$1@smc.vnet.net>
> I have a list that contains numeric and non-numeric values
> list = { a, 1, 2, b, 3};
> How can I replace non-numeric values with zeros?
This is the kind of thing the Mathematica does extremely well. At the
core of Mathematica is a very sophisticated pattern matching engine
around which everything else is built, so you want to take advantage
of that system as often and directly as possible. Here is one
solution:
ZeroNonNumeric[ (n_)?NumericQ ] := n;
ZeroNonNumeric[ _ ] := 0;
Map[ ZeroNonNumeric, {a, 1, 2, b, 3} ]
Out[1]= {0, 1, 2, 0, 3}
The first version of the function says that any for pattern for which
the predicate NumericQ[] returns False, throw back that pattern. The
second version says to return 0 for anything else. Mathematica will
always try the more specific patterns first, then try more general
patterns.
Finally, I Map that function over the list. Why do I use Map instead
of ZeroNonNumeric[ {a, 1, 2, b, 3} ] ? Simple: the list itself is not
a number. By Map'ping, I make sure that only the elements of the list
get checked, not the list itself.
There are more code-efficient ways of solving this, which all look
like perl code having a bad hair day. This solution spells out
exactly its intent, which is good practice in any language.