问题
My situation is:
I get a 1000*2 matrix and a 1000*1 vector.
And the row i in the matrix is mapped to the element i in the vector.
And the elements in the vector are all integer.
Now I want to sort the elements in the vector from low to high.
And I want to get a new matrix with the sequence of the new vector. And the mapping relationships are equal to the original situation.
How to do this in Matlab?
Thanks!
回答1:
Use sortrows:
First concat your vector to your matrix:
M2 = [V, M];
Then sort rows:
M2 = sortrows(M2); %// You should just do sortrows([V, M]) here, I just split it for the explanation
Then split the vector and the matrix:
V_sorted = M2(:,1);
M_sorted = M2(:, 2:end);
Or alternatively you can use the second output from sort:
[V_sorted, newRowOrder] = sort(V);
M_sorted = M(newRowOrder, :);
来源:https://stackoverflow.com/questions/19176189/how-to-sort-a-matrix-by-using-values-in-another-vector-in-matlab