3
$\begingroup$

I have a matrix

1,

and I want to sort it to obtain this matrix

1.

I tried SortBy, but I can only do it for 2 dimensional matrix. Can anyone help me?

$\endgroup$
  • 3
    $\begingroup$ 1) Post your matrix in form of an MMA code; 2) describe what is the general rule you want to employ in the sorting (I guess you don't just want to manually switch the columns). $\endgroup$ – corey979 Nov 6 '16 at 13:49
  • 1
    $\begingroup$ You want to sort it by the last element of the column? $\endgroup$ – Feyre Nov 6 '16 at 14:03
4
$\begingroup$

The easy way to do it is to strip off the outer brackets, sort, and then replace the outer brackets.

m = {{{4, 2, 2}, {27, 4, 1}, {12, 44, 6}, {32, 11, 11}, {44, 21, 5}}};
sorted = {SortBy[m[[1]], Last]}

{{{27, 4, 1}, {4, 2, 2}, {44, 21, 5}, {12, 44, 6}, {32, 11, 11}}}

sorted // MatrixForm

matrix

$\endgroup$
2
$\begingroup$

I would use the operator form:

m = {{{4, 2, 2}, {27, 4, 1}, {12, 44, 6}, {32, 11, 11}, {44, 21, 5}}};

SortBy[Last] /@ m
{{{27, 4, 1}, {4, 2, 2}, {44, 21, 5}, {12, 44, 6}, {32, 11, 11}}}
$\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.