23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Shifting and Sorting Matrices<br />

Sorting the Data in Each Column<br />

The sort function sorts matrix elements along a specified dimension. The<br />

syntax for the function is<br />

sort(matrix, dimension)<br />

To sort the columns of a matrix, specify 1 as the dimension argument. To sort<br />

along rows, specify dimension as 2.<br />

This example first constructs a 6-by-7 random matrix:<br />

rand('state', 0); % Initialize random number generator<br />

A = floor(rand(6,7) * 100);<br />

A =<br />

95 45 92 41 13 1 84<br />

23 1 73 89 20 74 52<br />

60 82 17 5 19 44 20<br />

48 44 40 35 60 93 67<br />

89 61 93 81 27 46 83<br />

76 79 91 0 19 41 1<br />

Sort each column of A in ascending order:<br />

c = sort(A, 1)<br />

c =<br />

23 1 17 0 13 1 1<br />

48 44 40 5 19 41 20<br />

60 45 73 35 19 44 52<br />

76 61 91 41 20 46 67<br />

89 79 92 81 27 74 83<br />

95 82 93 89 60 93 84<br />

issorted(c(:, 1))<br />

ans =<br />

1<br />

Sorting the Data in Each Row<br />

Use issorted to sort data in each row. Using the example above, if you sort<br />

each row of A in descending order, issorted tests for an ascending sequence.<br />

You can flip the vector to test for a sorted descending sequence:<br />

1-39

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!