Re: Tagged list processing
- To: mathgroup at smc.vnet.net
- Subject: [mg86914] Re: [mg86891] Tagged list processing
- From: Daniel Lichtblau <danl at wolfram.com>
- Date: Wed, 26 Mar 2008 04:52:33 -0500 (EST)
- References: <200803250617.BAA10618@smc.vnet.net>
carlos at colorado.edu wrote: > This is related to a recent question. Best stated through an example. > I have two flat lists of equal length: > > tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; > val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; > > tag contains only integers whereas val can have numbers or > expressions that will (eventually) evaluate to a number. > > Task. Generate a pointer list to all nz values in tag, and a > corresponding list of values: > > nztag={3,6,11,12,13}; (* may be empty *) > nzval={4,P,8,16.4,0}; (* may be empty *) > > and also build the complementary lists > > ztag={1,2,4,5,7,8,9,10,14,15}; > zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; > > Obviously ztag=Position[tag,0]; but which > form argument do I use for nztag in Position[tag,form]? > Can I build zval and nzval with Table for speed ? > (lists may contain 10^4 to 10^6 items) > > Constraint: must work in 4.0 thru 6.0 since some of my > remote students have legacy academic versions. Thanks. This will work for versions 5.0 through present, but not in 4.x. tagsAndValues[tag_List,val_List] := Module[ {n=Length[tag]}, Map[First,Reap[Do[If[tag[[j]]==0, Sow[j,ztag]; Sow[val[[j]],zval], Sow[j,nztag]; Sow[val[[j]],nzval]] , {j,n}], {nztag,nzval,ztag,zval}][[2]]] ] Example: {nztag,nzval,ztag,zval} = tagsAndValues[tag,val] In[4]:= InputForm[ {nztag,nzval,ztag,zval} = tagsAndValues[tag,val]] Out[4]//InputForm= {{3, 6, 11, 12, 13}, {4, P, 8, 16.4, 0}, {1, 2, 4, 5, 7, 8, 9, 10, 14, 15}, {0, 0, 5, 6, 1/2, 0, -3., 4 + a, Sin[ang], Cos[ang]}} For prior versions I'd suggest either using Position, or else emulating Sow/Reap using DownValue assignment. Other approaches will likely be noticeably slow, for lists in the size range you require. Daniel Lichtblau Wolfram Research
- Follow-Ups:
- Re: Re: Tagged list processing
- From: Daniel Lichtblau <danl@wolfram.com>
- Re: Re: Tagged list processing
- References:
- Tagged list processing
- From: carlos@colorado.edu
- Tagged list processing