海蓝无魂 发表于 2019-7-22 16:54:05

MATLAB技巧-sort和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表示的是按照降序或者升序排列(缺省的时候是升序排列)。

对于矩阵


按行升序:


按列升序:


从上述的结果看出,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,) sorts the rows of X first in ascending order
for the second column, and then by descending order for the third
column.

sortrows函数根据列col升序排序:
页: [1]
查看完整版本: MATLAB技巧-sort和sortrows函数