MATLAB和Python都提供了函数或对象的方法对表或DataFrame的行数据进行排序。根据参与排序的列的个数,可以有单条件排序和多条件排序。[大谦MATLAB,dqmatlab点com]
下面新建表T。
code.matlab
>> T=table({'张三';'李四';'杨二';'王五'},[18;19;17;25],...
[162;169;162;167], [116;103;131;133],'VariableNames',...
{'Name' 'Age' 'Height' 'Weight'});
使用sortrows函数,根据Height列数据的大小对表的行进行升序排列。
code.matlab
>> [B,index]=sortrows(T,"Height");
>> B
B =
4×4 table
Name Age Height Weight
________ ___ ______ ______
{'张三'} 18 162 116
{'杨二'} 17 162 131
{'王五'} 25 167 133
{'李四'} 19 169 103
使用sortrows函数,根据第3列数据的大小对表的行进行降序排列。
code.matlab
>> [B,index]=sortrows(T,3,'descend');
>> B
B =
4×4 table
Name Age Height Weight
________ ___ ______ ______
{'李四'} 19 169 103
{'王五'} 25 167 133
{'张三'} 18 162 116
{'杨二'} 17 162 131
使用sortrows函数,将Height列数据和Age列数据作为第1条件和第2条件对表的行进行升序排列。函数先根据Height列数据排序,对于Height数据相同的情况,再根据Age列数据的大小进行排序。
code.matlab
>> [B,index]=sortrows(T,["Height" "Age"]);
>> B
B =
4×4 table
Name Age Height Weight
________ ___ ______ ______
{'杨二'} 17 162 131
{'张三'} 18 162 116
{'王五'} 25 167 133
{'李四'} 19 169 103