Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
McHale, Paul

Posts: 60
Registered: 5/29/11
Re: Position
Posted: Jun 17, 2013 6:13 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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





Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.