matlab sort 2 columns: column 1 descending and column 2 ascending

后端 未结 2 480
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-27 12:29

I have a 3 column array like this:

A = [6 -1 0;
     6  0 3;
     1  4 3;
     1  2 5];

I need the first column to be in descending order and

相关标签:
2条回答
  • If the third column is to be unchanged,

     B = A;
     B(:,1) = sort(B(:,1),'descend');
     B(:,2) = sort(B(:,2),'ascend');
    

    If you want the third column to change with the second then,

    [B(:,2),ind] = sort(B(:,2),'ascend');
    B(:,3) = B(ind,3);
    
    B =
    
     6    -1     0
     6     0     3
     1     2     5
     1     4     3
    
    0 讨论(0)
  • 2021-01-27 13:08

    If you're looking to keep the rows intact as records, and sort them based on column 1 and then column 2, use sortrows(), with negative column indexes to indicate columns whose values are to be sorted in descending order.

    B = sortrows(A, [-1 2])
    
    0 讨论(0)
提交回复
热议问题