Skip to content

sortrows

general · scripts/general/sortrows.m

: [s, i] = sortrows (A)
: [s, i] = sortrows (A, c)
: [s, i] = sortrows (A, c, direction)
: [s, i] = sortrows (A, …, Name, Value)

Reorder the rows of A so that they are sorted.

Rows are compared column by column. Without c the first column is the primary key, the second breaks ties, and so on, all ascending. c lists the columns to use as keys, in order of priority; a negative entry sorts that column in descending order. direction is "ascend", "descend", or a cell of those (one overall, or one per key). Name-Value options are "MissingPlacement" ("auto", "first", "last") and "ComparisonMethod" ("auto", "abs", "real"). Character arrays are ordered lexicographically. The second output i is the permutation applied, so s = A(i, :).

Example: order by the second column, largest first, then by the third.

A = [ 7, 1, 4;
      8, 3, 5;
      9, 3, 6 ];
sortrows (A, [-2, 3])
   ⇒  8  3  5
      9  3  6
      7  1  4