Fast columns sorting of matrix refering another vector in matlab

前端 未结 1 1101
一整个雨季
一整个雨季 2021-01-24 23:32

I am trying to sort the columns of a matrix based on the another vector values in a fast way in matlab. Let assume I have a reference vector:

a = [1 8 3];


        
相关标签:
1条回答
  • 2021-01-25 00:16

    In Matlab the sort function returns two variables, the first is the sorted vector/matrix and the second is a set of indices that can be combined with the original data to produce the sorted values.

    A = [ 5 4 1 2 3 ];
    
    [A_sorted1, idx] = sort(A);
    
    A_sorted2 = A(idx);
    

    A_sorted1 and A_sorted2 are equivalent.

    If the number of rows in b is equal to the number of elements in a then you can simply use:

    [~, idx] = sort(a);
    b_sorted = b(idx,:);
    

    And if you want to sort by columns use:

    b_sorted = b(:,idx);
    
    0 讨论(0)
提交回复
热议问题