如何使用等级索引号对使用循环的其他数据集进行排序



我对Matlab很陌生,我的任务是使用Matlab来管理金融/经济数据库。

直接切入问题。假设我有两组数据,一组是A,另一组是B(见下文)。我的目标是根据值大小对3列进行排名,然后我想使用A的排名索引(sorted_index)来相应地定位B中的值。

下面是工作但非循环的解决方案,以获得我的答案:

A = [5 17 8; 11 2 9; 55 70 3; 11 8 33; 9 71 35; 9 2 3; 21 5 43; 5 2 9; 41 5 23; 61 72 91];
B = [1 2 3; 11 12 13; 21 22 23; 31 32 33; 1 2 3; 11 12 13; 21 22 23; 31 32 33; 41 42 43; 51 52 53];
[A_sorted sorted_index] = sort (A);
[B_sorted sorted_indexB] = sort (B);
B_sorted (:,1) = B(sorted_index(:,1),1);
B_sorted (:,2) = B(sorted_index(:,2),2);
B_sorted (:,3) = B(sorted_index(:,3),3);

B的结果(根据A的排名排序):1 12 2331 12 131 32 311 22 1311 42 3331 32 4321 2 3341 22 321 2 2351 52 53


问题是,如果我有2000列而不是只有3列,我怎么能成功地循环?

I tried this

for ii= size(B,2); jj= size(B,2) ; kk= size(B,2);
temp = 0*B;
temp(:,ii) = B(sorted_index(:,jj),kk);
B_sortedTest= temp;
end

但是它只给我最后一列的正确排序结果,前两列被覆盖(变成全零)。你能帮我解决这个问题吗?

非常非常感谢!

这是我的方法没有任何循环:

A = [5 17 8; 11 2 9; 55 70 3; 11 8 33; 9 71 35; 9 2 3; 21 5 43; 5 2 9; 41 5 23; 61 72 91];
B = [1 2 3; 11 12 13; 21 22 23; 31 32 33; 1 2 3; 11 12 13; 21 22 23; 31 32 33; 41 42 43; 51 52 53];
[A_sorted sorted_index] = sort (A);
% converting sorted_index into a vectorized form and having linear indices instead of subscripts i.e. 
% (row 2,column 3) in your sorted_index will be represented as 23=2*number of rows + 3=2*10+3.
linearSortedIndex=sub2ind(size(sorted_index),sorted_index(:),reshape(repmat((1:size(sorted_index,2),size(sorted_index,1),1).*ones(size(sorted_index)),[],1));
B_sorted1=reshape(B(linearSortedIndex),[],size(B,2));
%test that the result is correct
for i=1:size(B,2)
    B_sorted2(:,i) = B(sorted_index(:,i),i);
end
isequal(B_sorted1,B_sorted2) %If it prints 1, then this method is correct.

试试这个:

A = [5 17 8; 11 2 9; 55 70 3; 11 8 33; 9 71 35; 9 2 3; 21 5 43; 5 2 9; 41 5 23; 61 72 91];
B = [1 2 3; 11 12 13; 21 22 23; 31 32 33; 1 2 3; 11 12 13; 21 22 23; 31 32 33; 41 42 43; 51 52 53];
[A_sorted sorted_index] = sort (A);
[B_sorted sorted_indexB] = sort (B);
for i=1:size(B,2)
    B_sorted (:,i) = B(sorted_index(:,i),i);
end

最新更新