Re: Re: Binary Vector Manipulation
- To: mathgroup at smc.vnet.net
- Subject: [mg84167] Re: [mg84112] Re: Binary Vector Manipulation
- From: DrMajorBob <drmajorbob at bigfoot.com>
- Date: Wed, 12 Dec 2007 05:12:15 -0500 (EST)
- References: <fjj183$frv$1@smc.vnet.net> <27344701.1197389547252.JavaMail.root@m35>
- Reply-to: drmajorbob at bigfoot.com
Brilliant! That has linear complexity (apparently) and, for n=10^6, it's 30 times faster than my solution. I rewrote it to eliminate a Total, but it hardly mattered: muench[a_, b_] := Block[{newB = Clip[a + b], posns}, posns = Position[Normal@newB, 1]; ReplacePart[newB, RandomSample[posns, Length@posns - Total@b] -> 0]] Bobby On Mon, 10 Dec 2007 19:39:28 -0600, thomas <thomas.muench at gmail.com> wrote: > One of several possibilities is > > With[{newB = Clip[vectorA + vectorB]}, > ReplacePart[newB, > RandomSample[Position[Normal@newB, 1], Total[newB] - Total[vectorB]] > -> > 0]] > > where newB is your new vector with "more than 50%" 1's. It is achieved > by adding vectorA and vectorB, yielding some "2" entries where the "1" > entries between A and b overlapped. Clip[...] corrects for that. > > In the second part you randomly replace the appropriate number of 1's > with 0's. You get this number with Total[newB] - Total[vectorB], which > is the number of excess 1's in newB. You need the "Normal@" in > "Position[Normal@newB, 1]" only if your original vectors were > SparseArrays, because Position doesn't work with SparseArrays. > > another option [maybe faster, depending on the size of your vectors]: > > SparseArray[ > RandomSample[ > SparseArray@Clip[vectorA + vectorB]/. > SparseArray[_, _, _, p_] :> Flatten@p[[2, 2]], Total[vectorB]] -> > Table[1, {Total[vectorB]}]] > > > Hope that helps, > Thomas > > On Dec 10, 10:34 am, Tara.Ann.Lor... at gmail.com wrote: >> I am need of assistance programming the following scenario: >> >> I have two vectors composed of 0's and 1's. Vector "A" has 5% 1's >> (and 95% 0's) while Vector "B" has 50% 1's and 50% 0's. >> >> First, I would like to change Vector B to have a "1" in every place >> that Vector A also has a "1" (in other words, I will then have more >> than 50% 1's in Vector B once this step is completed). >> >> Then, I would like to *randomly* return Vector B back to a 50/50 >> distribution of 1's and 0's. >> >> I greatly appreciate any proposed programming methods. >> >> Thank you, >> Tara > > -- DrMajorBob at bigfoot.com