MathGroup Archive 2013

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

Search the Archive

Re: Position

  • To: mathgroup at
  • Subject: [mg131196] Re: Position
  • From: "McHale, Paul" <Paul.McHale at>
  • Date: Mon, 17 Jun 2013 06:24:51 -0400 (EDT)
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:

This is something I run into a lot.  I think there are many ways to solve it and many have been listed.  To me, there are three approaches which will allow me to have found something in a list and preserved it's place in the list.

1. Using something that naturally operates on index.  I.e. For[]
2. Adding index to list, then selecting base on value.  I.e. Table[] or Range[]/Riffle[]
3. Getting list of positions within list and matching up to data.  I.e. Position[]

Generate list "m"
   m = RandomInteger[{1, 1000}, 1000];

I prefer Table[] as I am most comfortable with it.  I add the index to every list member and then select the members that I want.  Not memory efficient.  I like it because people can see what the list elements will look like. [{index,m[[index]]}

   m2=Select[mPos,#[[2]] > 500 &]

I think this is less obvious (for newbies), but works just as well

   mPos = Partition[Riffle[Range[Length[m]], m], 2];
   m3 = Select[mPos, #[[2]] > 500 &]

Probably the most memory efficient was mentioned by others.  Find the position and retrieve only the needed values into new list.

   mPos=Position[m,x_ /; x > 500] // Flatten;

> m1==m2==m3
( Not that his is conclusive, but even I would have a hard time screwing it up three different ways and having identical results.  This is a serious benefit of Mathematica over other languages and is probably one of the greatest tools I have for minimizing defects.   I see other people here doing it as well.)

I don't use the For[] loop because I think it does not fit well.  It is clumsy for functional programming.  It is also awkward for people who are used to traditional language for loops due to everything being a parameter to For[].  Just my opinion. 

Paul McHale  |  Electrical Engineer, Energetic Systems   |  Excelitas Technologies Corp.

Office: +1 937.865.3004   |  Fax: +1 937.865.5170
1100 Vanguard Boulevard, Miamisburg, OH  45342-0312
Paul.McHale at

  • Prev by Date: Re: Multiplication by 0: non-zero in versions 8 and 9
  • Next by Date: Axes in Plot3D and ListPlot3D
  • Previous by thread: Re: Position
  • Next by thread: Applying data from a database link to a GraphPlot