Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Position
Replies: 8   Last Post: Jun 17, 2013 6:13 AM

 Messages: [ Previous | Next ]
 McHale, Paul Posts: 60 Registered: 5/29/11
Re: Position
Posted: Jun 17, 2013 6:13 AM

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]]}

mPos=Table[{index,m[[index]]},{index,1,Length[m]}];
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=Map[{#,Take[m,{#}][[1]]}&,mPos]

> m1==m2==m3
True
( 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@Excelitas.com
www.excelitas.com

Date Subject Author
6/14/13 Bob Hanlon
6/14/13 Harvey P. Dale
6/14/13 Harvey P. Dale
6/14/13 waku
6/14/13 Ray Koopman
6/14/13 Tomas Garza Hernandez
6/15/13 Dr.J
6/17/13 McHale, Paul