Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting with changes to the other part in mathematica

I am just wondering:

given a list {{{3,1,2},{4,2,5}},{{7,1},{2,4}}}, I want to sort the first component, then have the second component change as the first one does. The desired result is {{{1,2,3},{2,5,4}},{{1,7},{4,2}}}.

How can I do this? Many thanks for your help.

like image 564
Qiang Li Avatar asked Dec 09 '22 10:12

Qiang Li


2 Answers

Here's the job-security-ensuring one-liner =)

In[16]:= list={{{3,1,2},{4,2,5}},{{7,1},{2,4}}};

In[17]:= {#[[Ordering[#]]],#2[[Ordering[#]]]}& @@@ list
Out[17]= {{{1,2,3},{2,5,4}},{{1,7},{4,2}}}

This might be a little more clear as to what's happening:

sorter[{a_, b_}] :=
 Module[{order = Ordering[a]},
  {a[[order]], b[[order]]}
  ]

In[19]:= sorter /@ list

Out[19]= {{{1, 2, 3}, {2, 5, 4}}, {{1, 7}, {4, 2}}}
like image 50
Michael Pilat Avatar answered Dec 11 '22 23:12

Michael Pilat


I suggest:

#[[ All, Ordering@#[[1]] ]] & /@ list

This is shorter than Michael's, and nearly twice as efficient.

micSort = {#[[Ordering[#]]], #2[[Ordering[#]]]} & @@@ # &;

wizSort = #[[All, Ordering@#[[1]]]] & /@ # &;

a = RandomInteger[100, {2400, 2, 15}];

micSort@a === wizSort@a
First@Timing@Do[#@a, {25}] & /@ {micSort, wizSort}

Out[1]= True

Out[2]= {0.453, 0.282}
like image 41
Mr.Wizard Avatar answered Dec 11 '22 23:12

Mr.Wizard