1
$\begingroup$

Consider the data

data = {{x1,y1,z1},{x2,y2,z2},{x3,y3,z3},{x4,y4,z4},{x5,y5,z5},{x6,y6,z6},...}

with N rows.

It can be divided into N/3 sets of 3 rows. I would like to sort the data in a way such that the rows inside the each set will be aligned according to the growth of y parameter. Finally, if yi = yj, then the upper row must be the one for which xi > xj.

For example, if y2 > y1 > y3 and y6 > y5 = y4, and x4 > x5, then it must be

datasorted = {{x2,y2,z2},{x1,y1,z1},{x3,y3,z3},{x6,y6,z6},{x4,y4,z4},{x5,y5,z5},...}

Could you please tell me how to do this?

$\endgroup$
  • 1
    $\begingroup$ SortBy[#, {-#[[2]] &, -#[[1]] &}] & /@ Partition[data, n/3]? $\endgroup$ – kglr Feb 25 at 23:11
  • 1
    $\begingroup$ @kglr I think you meant Partition[data, 3]? But OP has added an additional requirement now. $\endgroup$ – Rohit Namjoshi Feb 25 at 23:14
  • $\begingroup$ @kglr : thank you! However, because of my stupidness I forgot to include additional requirement to my question before you commented... $\endgroup$ – John Taylor Feb 25 at 23:14
  • 1
    $\begingroup$ ReverseSort[data[[All, {2, 1, 3}]]][[All, {2, 1, 3}]]? $\endgroup$ – Henrik Schumacher Feb 25 at 23:21
  • 1
    $\begingroup$ @RohitNamjoshi, right.; thank you. $\endgroup$ – kglr Feb 25 at 23:22
3
$\begingroup$

You can map SortBy[#, {-#[[2]] &, -#[[1]] &}] & on your partitioned data:

SeedRandom[1]
data = RandomInteger[5, {15, 3}];
partitioned = Partition[data, 3];
MatrixForm[MatrixForm /@ partitioned, TableDirections -> Row]

$\left( \begin{array}{ccccc} \left( \begin{array}{ccc} 4 & 2 & 4 \\ 0 & 1 & 0 \\ 0 & 2 & 0 \\ \end{array} \right) & \left( \begin{array}{ccc} 0 & 3 & 5 \\ 2 & 0 & 3 \\ 4 & 4 & 1 \\ \end{array} \right) & \left( \begin{array}{ccc} 3 & 3 & 4 \\ 1 & 4 & 2 \\ 1 & 1 & 4 \\ \end{array} \right) & \left( \begin{array}{ccc} 5 & 4 & 5 \\ 0 & 3 & 3 \\ 0 & 0 & 2 \\ \end{array} \right) & \left( \begin{array}{ccc} 3 & 1 & 1 \\ 3 & 2 & 5 \\ 1 & 1 & 4 \\ \end{array} \right) \\ \end{array} \right)$

MatrixForm[MatrixForm /@ (SortBy[#, {-#[[2]] &, -#[[1]] &}] & /@ partitioned), 
 TableDirections -> Row]

$\left( \begin{array}{ccccc} \left( \begin{array}{ccc} 4 & 2 & 4 \\ 0 & 2 & 0 \\ 0 & 1 & 0 \\ \end{array} \right) & \left( \begin{array}{ccc} 4 & 4 & 1 \\ 0 & 3 & 5 \\ 2 & 0 & 3 \\ \end{array} \right) & \left( \begin{array}{ccc} 1 & 4 & 2 \\ 3 & 3 & 4 \\ 1 & 1 & 4 \\ \end{array} \right) & \left( \begin{array}{ccc} 5 & 4 & 5 \\ 0 & 3 & 3 \\ 0 & 0 & 2 \\ \end{array} \right) & \left( \begin{array}{ccc} 3 & 2 & 5 \\ 3 & 1 & 1 \\ 1 & 1 & 4 \\ \end{array} \right) \\ \end{array} \right)$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.