Re: Sorting point-arrays by rows and columns, cont.
- To: mathgroup at smc.vnet.net
- Subject: [mg124060] Re: Sorting point-arrays by rows and columns, cont.
- From: Chris Young <cy56 at comcast.net>
- Date: Sat, 7 Jan 2012 05:23:17 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <je6e3j$q6k$1@smc.vnet.net>
Thanks to Fred Simons for this method. Seems to work fine and seems to be one of the simplest to use in this particular case. Still wish that Sort would just accept a list of successive conditions to break ties, as SortBy does. (SortBy, however, applies the functions to every element and _then_ sorts, not what we want here.) In[3]:= Sort[hexPts, #1[[2]] < #2[[ 2]] \[Or] (#1[[2]] == #2[[2]] && #1[[1]] <= #2[[1]]) & ] Out[3]= {{-(1/2), -(Sqrt[3]/2)}, {1/2, -(Sqrt[3]/2)}, {-1, 0}, {0, 0}, {1, 0}, {-(1/2), Sqrt[3]/2}, {1/2, Sqrt[3]/2}} To DrMajorBob: Thanks for the example with Ordering, but I'm not sure why it would be necessary here, if Sort works just as well: Here's an ordering for irrationals on the second element: In[4]:= pts = {{0, 2}, {1, Sqrt[2]}, {2, 2}, {4, 1}, {Sqrt[5], 1}, {6, 1}, {Sqrt[3], 1}, {7, 0}, {-1, 0}}; In[5]:= pts[[Ordering[pts[[All, 2]], All, Less]]] Out[5]= {{-1, 0}, {7, 0}, {Sqrt[3], 1}, {6, 1}, {Sqrt[5], 1}, {4, 1}, {1, Sqrt[2]}, {2, 2}, {0, 2}} In[21]:= pts[[Ordering[pts[[All, 2]], All, #1 < #2 &]]] Out[21]= {{-1, 0}, {7, 0}, {Sqrt[3], 1}, {6, 1}, {Sqrt[5], 1}, {4, 1}, {1, Sqrt[2]}, {2, 2}, {0, 2}} It seems that we can do the same quicker with Sort: In[25]:= Sort[pts, #1[[2]] < #2[[2]] &] Out[25]= {{-1, 0}, {7, 0}, {Sqrt[3], 1}, {6, 1}, {Sqrt[5], 1}, {4, 1}, {1, Sqrt[2]}, {2, 2}, {0, 2}} Thanks for the examples with Fold, which I'm going to continue to work through, but I wasn't able to get it to sort the 2nd elements correctly: In[10]:= threes = RandomChoice[Flatten[pts], {10, 3}] Out[10]= {{1, 2, 0}, {1, Sqrt[2], 1}, {1, 7, 2}, {1, 1, Sqrt[5]}, {1, 2, 2}, {0, 4, -1}, {0, 2, 1}, {7, 1, 0}, {1, Sqrt[5], 2}, {0, 2, -1}} (The following doesn't seem to work!! We have Sqrt[5] in the 2nd coordinate coming before 1 in the last two vectors. Don't understand why Reverse was needed, and also why {3,1} was used. What does the {3,1} to?) In[35]:= Fold[#1[[Ordering[#1[[All, #2]], All, LessEqual]]] &, threes, Reverse@{3, 1}] Out[35]= {{0, 4, -1}, {0, 2, -1}, {1, 2, 0}, {7, 1, 0}, {0, 2, 1}, {1, Sqrt[2], 1}, {1, 7, 2}, {1, 2, 2}, {1, Sqrt[5], 2}, {1, 1, Sqrt[5]}} In[29]:= N[%26, 2] Out[29]= {{0, 4.0, -1.0}, {0, 2.0, -1.0}, {1.0, 2.0, 0}, {7.0, 1.0, 0}, {0, 2.0, 1.0}, {1.0, 1.4, 1.0}, {1.0, 7.0, 2.0}, {1.0, 2.0, 2.0}, {1.0, 2.2, 2.0}, {1.0, 1.0, 2.2}}