How to sort a matrix by using values in another vector in matlab?

十年热恋 提交于 2021-02-11 05:10:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!