sortrows

Returns matrix, R, which is the result of sorting rows of matrix, m, based on the columns listed, columns.

Syntax

R = sortrows(m)

R = sortrows(m, columns)

[R, index] = sortrows(m, ...)

Inputs

m
Type: matrix
columns (optional)
Specifies the order of columns used for sorting. If a column number is negative, sorting is done in descending order, else sorting is done in ascending order. If no column is specified, the first column is used for sorting
Type: integer | vec

Outputs

R
Type: matrix
index
Vector which contains the indicies of the rows of the input matrix, m, which make up the sorted resultant matrix, R.
Type: vector

Examples

Sort matrix using the first column as the reference in ascending order:
R = sortrows([8, 1, 2, 6; 7, 4, 8, 5; 8, 4, 9, 4 ])
R = [Matrix] 3 x 4
7  4  8  5
8  1  2  6
8  4  9  4
Sort matrix using multiple columns, in ascending and descending order:
R = sortrows([8, 1, 2, 6; 7, 4, 8, 5; 8, 4, 9, 4], [1, -2])
R = [Matrix] 3 x 4
7  4  8  5
8  4  9  4
8  1  2  6
Sort matrix using multiple columns and get row indicies in original matrix:
[s,idx]=sort([1,2,3,4],'ascend')
s = [ 1 2 3 4 ]
idx = [ 1 2 3 4 ]
Two outputs with dim and descend specified:
[R, index] = sortrows([8, 1, 2, 6; 7, 4, 8, 5; 8, 4, 9, 4], [1, -2])
R = [Matrix] 3 x 4
7  4  8  5
8  4  9  4
8  1  2  6
index = [Matrix] 3 x 1
2
3
1