MATLAB技巧——sort和sortrows函数

时间:2022-05-04
本文章向大家介绍MATLAB技巧——sort和sortrows函数,主要内容包括1、sort函数、2、sortrows函数、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

1、sort函数

sort函数用于对数据进行排序,通过help sort命令,可以查找到sort函数的具体用法:

Y = SORT(X,DIM,MODE)
has two optional parameters.  
DIM selects a dimension along which to sort.
MODE selects the direction of the sort
   'ascend' results in ascending order
   'descend' results in descending order
The result is in Y which has the same shape and type as X.

上面的意思是说,在sort函数中,有两个参数,一个参数是dim,dim表示的是按照哪一维排序,如行为1,列为2;第二个参数是mode,mode表示的是按照降序或者升序排列(缺省的时候是升序排列)。

对于矩阵

A=begin{pmatrix} 5 & 7 & 8 \ 4 & 6 & 1 \ 8 & 0 & 7 end{pmatrix}

按行升序:

按列升序:

从上述的结果看出,sort函数会比较矩阵中的每一个元素,将行中的每一个元素或者列中的每一个元素按照升序排列。

若现在需要将矩阵按照行排序,可以任意指定排序比较的列。可以使用sortrows函数。

2、sortrows函数

SORTROWS(X,COL) sorts the matrix based on the columns specified in the
vector COL.  If an element of COL is positive, the corresponding column
in X will be sorted in ascending order; if an element of COL is negative,
the corresponding column in X will be sorted in descending order. For 
example, SORTROWS(X,[2 -3]) sorts the rows of X first in ascending order 
for the second column, and then by descending order for the third
column.

sortrows函数根据列col升序排序: