Skip to content

sortrows

Sort rows of a matrix or table by column values.

B = sortrows(A)
[B, IX] = sortrows(A)
B = sortrows(A, columns)

Returns a matrix with the rows of A sorted lexicographically by column. With no columns argument, sorts by column 1, breaking ties by column 2, etc. With columns (a scalar or vector of column indices), sorts by those columns in order; negative values sort that column in descending order.

The optional second output IX is the row permutation that produced the sort: B == A(IX, :).

A = [3 1; 1 2; 3 0];
sortrows(A) % [1 2; 3 0; 3 1] (col 1 asc, then col 2 asc)
sortrows(A, [1 -2]) % [1 2; 3 1; 3 0] (col 1 asc, col 2 desc)
[B, IX] = sortrows(A);
isequal(A(IX, :), B) % 1
  • circshift — Circularly shift elements of an array.
  • fliplr — Flip an array left-to-right (reverse columns).
  • flipud — Flip an array upside down (reverse rows).