Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Replacing Numbers in a List

  • To: mathgroup at smc.vnet.net
  • Subject: [mg68339] Re: Replacing Numbers in a List
  • From: Rolf.Mertig at gmail.com
  • Date: Tue, 1 Aug 2006 07:00:15 -0400 (EDT)
  • References: <eahsgh$op1$1@smc.vnet.net><eakkuv$2f4$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Paul Abbott schrieb:
...
> No one has suggested the obvious
>
>   x /. Thread[y -> 222]
>
> However, this is about twice as slow as Bob Hanlon's suggestion,
>
>   If[MemberQ[y,#],222,#]& /@ x
>
> Test:
>
>   y={122,211,212,221,223,232,322};
>
>   x=Table[Random[Integer,{100,325}],{10^5}];
>
>   Timing[x1 = x /. Thread[y -> 222];] // First
>   0.051946 Second
>
>   Timing[x2 = If[MemberQ[y,#],222,#]& /@ x;] // First
>   0.037817 Second
>
>   x1 == x2
>   True
>
> Cheers,
> Paul
>
> _______________________________________________________________________
> Paul Abbott                                      Phone:  61 8 6488 2734
> School of Physics, M013                            Fax: +61 8 6488 1014
> The University of Western Australia         (CRICOS Provider No 00126G)
> AUSTRALIA                               http://physics.uwa.edu.au/~paul

The quickest seems to be to add Dispatch (sometimes I wonder why
Mathematica does not use Dispatch automatically).

In[1]:= !!r
Print[$Version];
y = {122, 211, 212, 221, 223, 232, 322};
x0=x= Table[Random[Integer, {100, 333}], {10^6}];
Print["x1: ",Timing[x1 = x /. Thread[{122, 211, 212, 221, 223, 232,
322} ->222];]];
Print["x2: ", Timing[x2 = x /. Dispatch[Thread[{122, 211, 212, 221,
223, 232, 322} ->222]];]]
Print["x3: ",Timing[Do[x = ReplacePart[x,222, Position[x, y[[i]]]],{i,
Length@y} ]; x3=x;]];
Print["x4: ",Timing[x4=If[MemberQ[y,#],222,#]&/@x0;]];
x1===x2===x3===x4

In[1]:= <<r
5.2 for Linux x86 (64 bit) (June 20, 2005)
x1: {0.396024 Second, Null}
x2: {0.256017 Second, Null}
x3: {0.768048 Second, Null}
x4: {0.412025 Second, Null}

Out[1]= True

Rolf
----------------------------------------------------
Dr. Rolf Mertig
GluonVision GmbH
Berlin, Germany
http://www.gluonvision.com


  • Prev by Date: Re: Re: Re: InputForm changes the order of output?
  • Next by Date: Re: Problem solving a difference equation
  • Previous by thread: Re: Re: Replacing Numbers in a List
  • Next by thread: Re: Re: {x},{y} -> {x,y} ?