在Matlab中引用另一个向量的矩阵的快速列排序 [英] Fast columns sorting of matrix refering another vector in matlab
问题描述
我正在尝试根据一个矩阵中的另一个向量值对矩阵的列进行排序 在Matlab中的快速方法. 假设我有一个参考向量:
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];
我想按行排序的矩阵
b =[2 3 4
5 6 4
1 2 1];
如果排序的a是
a = [8 3 1]
排序后的矩阵现在为
b = [3 4 2
6 4 5
2 1 1];
因此第一个向量的索引与列的索引相同 因此,我们根据向量的值对列进行排序.
So the index of the first vector is the same with the index of the columns So we sort columns based on the values of the vector.
推荐答案
在Matlab中, sort
函数返回两个变量,第一个是排序后的向量/矩阵,第二个是可以与原始数据组合以产生排序后的值的一组索引.
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
和A_sorted2
是等效的.
如果b
中的行数等于a
中的元素数,则可以简单地使用:
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);
这篇关于在Matlab中引用另一个向量的矩阵的快速列排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!