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];
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);