Sorting in Matlab

| categories: miscellaneous | View Comments

Sorting in Matlab

Sorting in Matlab

John Kitchin

Occasionally it is important to have sorted data. Matlab provides a sort command with a variety of behaviors that you can use, as well as other related commands.

Contents

Sorting a vector

a = [4 5 1 6 8 3 2]
a =

     4     5     1     6     8     3     2

b_ascending = sort(a)  % default is in ascending order
b_ascending =

     1     2     3     4     5     6     8

You can specify descending order like this

b_descending = sort(a,'descend')
b_descending =

     8     6     5     4     3     2     1

or you can use the command fliplr to reverse the vector sorted in ascending order.

fliplr(b_ascending)
ans =

     8     6     5     4     3     2     1

Sorting a matrix

If you have data organized in a matrix, you need to be aware of what sorting means. You can sort rows or columns!

a = [5 1 5 4 3
     0 7 1 2 3];

 sort(a)
ans =

     0     1     1     2     3
     5     7     5     4     3

sort works columnwise by default. If you wanted the rows sorted, you need:

sort(a,2)
ans =

     1     3     4     5     5
     0     1     2     3     7

How can you remember that? Indexing in Matlab is (row,column). This notation means sort along the columns. In other words, the row is fixed, and you sort along the columns.

Where would this ever come up? We use it in cmu.der.derc to ensure the x-values are in ascending order before we compute the derivative! It is also convenient to sort data before plotting it if you connect the datapoints by lines.

x = [9 1 2 5 6 7];
y = sin(x);

plot(x,y)

Note how the lines cross each other. That is visually distracting, and simply an artifact of the ordering of the points. We can use an extra feature of sort to sort x and y, so that x is sorted in ascending order, and we use the change in the order of x to get the corresponding changes in y. This is a handy trick!

[X I] = sort(x);
Y = y(I);
plot(X,Y)
'done'

% categories: Miscellaneous
ans =

done

blog comments powered by Disqus