Re: Better Way of Testing and Replacing List Elements?
- To: mathgroup at smc.vnet.net
- Subject: [mg103993] Re: Better Way of Testing and Replacing List Elements?
- From: Januk <ggroup at sarj.ca>
- Date: Thu, 15 Oct 2009 07:15:05 -0400 (EDT)
- References: <hb3fus$lsk$1@smc.vnet.net>
There are many options. From fast to slow:
xxx = RandomInteger[{-10, 10}, 10^6];
Use Clip:
y2 = Clip[xxx, {0, \[Infinity]}]; // Timing
Use UnitStep:
y3 = (# * UnitStep[#])& @ xxx; // Timing
Use pattern replacement:
y4 = xxx /. {x_?(# < 0 &) :> 0}; // Timing
Create a function:
f[x_?(# < 0 &)] := 0
f[x_] := x
y5 = f /@ xxx; // Timing
Your original solution:
y1 = ReplacePart[xxx, Position[Map[Negative, xxx], True] -> 0]; //
Timing
Create a piecewise function:
g[x_] := Piecewise[{{x, x >= 0}}]
y6 = g /@ xxx; // Timing
Hope that helps,
Januk
On Oct 13, 11:18 pm, careysub <carey... at gmail.com> wrote:
> The code below replaces the negative values in a list with zero, and
> is an example of a type of operation I use a lot:
>
> xxx = {1, 2, 3, 4, 5, -6, -7, 8, 9, 10, -1, 11, 12};
> ReplacePart[xxx, Position[Map[Negative, xxx], True] -> 0]
>
> Is there a "better" way of doing this (fewer function calls, more
> efficient)?
>
> My feeling is that I'm doing this in an awkward way.