MathGroup Archive 2008

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

Search the Archive

Re: Clever way to manipulate lists

  • To: mathgroup at smc.vnet.net
  • Subject: [mg94392] Re: Clever way to manipulate lists
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Thu, 11 Dec 2008 07:28:16 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <ghqjve$14i$1@smc.vnet.net>

guerom00 wrote:

> I'm still struggling through lists manipulation. I'll take a concrete
> example to illustrate my point.
> Let's say I have a first list, say coordinates on a regular grid :
> 
> list1={{x1,y1},{x2,y2},{x3,y3}...{xN,yN}}
> 
> This obviously has a Length of N. Now, let's say I have a second list.
> In this one, there are fewer than N elements, some points are
> missing... Let's say it misses a point at x2 :
> 
> list2 ={{x1,z1},{x3,z3},{x4,z4}...{xN,zN}}
> 
> Now, since those two lists are not of the same length, I cannot add
> them, substract them or something. But list2 is included in list1 (in
> the sense of set theory). Now, what I want to do is, in this example,
> remove the point {x2,y2} from list1 and then the two list will have
> the same length and I'll be able to manipulate them as I want.
> Right now, I do that with For loops (detect elements which are in
> list1 and not in list2 and delete them, etc...) and that works but it
> is not elegant.
> I'm looking for a concise, elegant way to do that if somebody sees
> what I mean...

You could use *Intersection[]* with a custom test specifying that the 
first value of each pair must be the same, that is

   Intersection[list1, list2, SameTest -> (#1[[1]] === #2[[1]] &)]

Here are a couple of examples.

   In[1]:=
   list1 = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, z4}, {xN, yN}};
   list2 = {{x1, z1}, {x3, z3}, {x4, z4}, {xN, zN}};

   Intersection[list1, list2, SameTest -> (#1[[1]] === #2[[1]] &)]

   Out[3]= {{x1, y1}, {x3, y3}, {x4, z4}, {xN, yN}}

   In[4]:=
   nPts = 5;
   xvals = RandomReal[1, {nPts}]
   list1 = Transpose[{xvals, RandomReal[1, {nPts}]}]
   list2 = Delete[Transpose[{xvals, RandomReal[1, {nPts}]}], {{2}, {5}}]

   Intersection[list1, list2, SameTest -> (#1[[1]] === #2[[1]] &)]

   Out[5]= {0.362094, 0.404047, 0.337005, 0.894055, 0.164118}

   Out[6]= {{0.362094, 0.42105}, {0.404047, 0.141265}, {0.337005,
     0.634139}, {0.894055, 0.645911}, {0.164118, 0.811351}}

   Out[7]= {{0.362094, 0.62147}, {0.337005, 0.733766}, {0.894055,
     0.151596}}

   Out[8]= {{0.337005, 0.634139}, {0.362094, 0.42105}, {0.894055,
     0.645911}}

Regards,
-- Jean-Marc


  • Prev by Date: Re: Small question about Filling between two functions in a determined interval
  • Next by Date: Re: Run initialization cells before dynamic cells
  • Previous by thread: Re: Clever way to manipulate lists
  • Next by thread: Re: Clever way to manipulate lists