简体   繁体   English

如何使用matlab中另一个向量中的值对矩阵进行排序?

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

My situation is: 我的情况是:

I get a 1000*2 matrix and a 1000*1 vector. 我得到1000 * 2矩阵和1000 * 1向量。

And the row i in the matrix is mapped to the element i in the vector. 并且矩阵中的行i被映射到向量中的元素i。

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? 如何在Matlab中做到这一点?

Thanks! 谢谢!

Use sortrows : 使用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 : 或者您也可以使用sort的第二个输出:

[V_sorted, newRowOrder] = sort(V);
M_sorted = M(newRowOrder, :);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM