Re: Re: choose elements from list based on elements in different list
- To: mathgroup at smc.vnet.net
- Subject: [mg86800] Re: [mg86734] Re: choose elements from list based on elements in different list
- From: DrMajorBob <drmajorbob at bigfoot.com>
- Date: Fri, 21 Mar 2008 01:54:43 -0500 (EST)
- References: <frqpnb$4vl$1@smc.vnet.net> <9299042.1206024293207.JavaMail.root@m08>
- Reply-to: drmajorbob at longhorns.com
Inner does SEEM a natural way to go, but see below, where my "bt" is a bit
faster than David's "dp".
n= 10^6;
Clear[ dp,bt,zeroQ]
SetAttributes[ zeroQ,Listable]
zeroQ[0]=True;
zeroQ[_]=False;
dp[ a_List,b_List]:= Inner[ If[ #1==0\[And] #2!=0,#2, Unevaluated@
Sequence[]]&,a,b,List]
bt[ a_List,b_List]:= Pick[ b, Transpose[ zeroQ/@ { a,b}], { True,False}]
one= RandomInteger[ GeometricDistribution[0.1],n];
two= RandomInteger[ GeometricDistribution[0.1],n];
test[ a_List,b_List]:= Module[ { t1,t2,r1,r2}, { t1,r1}= Timing@
dp[ a,b]; { t2,r2}= Timing@ bt[ a,b]; { t1,t2, r1==r2}]
test[ one,two]
{5.53549000000001, 1.3797390000000007, True}
test[two, one]
{5.561236000000008, 1.3858140000000105, True}
Oddly enough, BTW, replacing zeroQ by the built-in PossibleZeroQ slows "b"
by a factor of more than 30.
Still and all, Inner is the far simpler way to think of it, I suppose.
Bobby
On Thu, 20 Mar 2008 02:50:34 -0500, David Park <djmpark at comcast.net> wrote:
> Whenever one wants to do operations on two equal length structures the
> Inner
> statement is a good choice.
>
> Reihe1 = {22, 33, 44, 0, 0, 16, 5, 0, 0, 0};
> Reihe2 = {16, 27, 0, 0, 5, 11, 5, 0, 0, 12};
>
> Here we do the two tests and either insert the nonzero number in a new
> list,
> or insert an empty Sequence. The empty Sequence must be Unevaluated in
> the
> If statement or it would simply disappear for there.
>
> Inner[If[#1 == 0 \[And] #2 != 0, #2,
> Unevaluated@Sequence[]] &, Reihe1, Reihe2, List]
> {5, 12}
>
> Inner[If[#2 == 0 \[And] #1 != 0, #1,
> Unevaluated@Sequence[]] &, Reihe1, Reihe2, List]
> {44}
>
> This construction is also useful for the combination of equations.
>
> eqn1 = x == a + b;
> eqn2 = y == a - b;
>
> Inner[#1 + #2 &, eqn1, eqn2, Equal]
> x + y == 2 a
>
> Inner[Expand[2 #1 - #2] &, eqn1, eqn2, Equal]
> 2 x - y == a + 3 b
>
-- =
DrMajorBob at longhorns.com