Multiple columns

Nested sort of a matrix based on multiple columns

% sort data first by colum 1, then by column 2, and finally by column 3

sortrows(data,[1,2,3])

Example

% create a data table with three columns ("Subject" "Treatment" "Time" )

data = [1 1 1

2 1 1

3 1 1

1 2 1

2 2 1

3 2 1

1 1 2

2 1 2

3 1 2

1 2 2

2 2 2

3 2 2]

% sort data table first using column 1, then using column 2, and finally column 3

[data_sorted, sort_index] = sortrows(data, [1,2,3])

data_sorted =

1 1 1

1 1 2

1 2 1

1 2 2

2 1 1

2 1 2

2 2 1

2 2 2

3 1 1

3 1 2

3 2 1

3 2 2

Index of how the rows are re-ordered

sort_index =

1

7

4

10

2

8

5

11

3

9

6

12

data_sorted = data(sort_index,:)