我有一个排序的bigmatrix.但是,我需要按照另一个矩阵(col. 1 here for both matrices
)中ID的顺序重新排序.我怎么能用矢量化呢?例如:
bigmat = [ ...
1 10 ;
1 30 ;
1 40 ;
2 1 ;
2 11 ;
3 58 ;
4 2 ;
4 5 ] ;
ordermat = [ 2 ; 1 ; 4 ; 3 ; 6] ; % Integer IDs
finalans = [ ...
2 1 ;
2 11 ;
1 10 ;
1 30 ;
1 40 ;
4 2 ;
4 5 ;
3 58 ; ] ;
Run Code Online (Sandbox Code Playgroud)
ordermat
在bigmat 中可能不存在所有一些ID(此处为整数).它们可以被忽略,如上所示id = 6
.谢谢!
%# Input values:
bigmat = [1 10; 1 30; 1 40; 2 1; 2 11; 3 58; 4 2; 4 5];
ordermat = [ 2 ; 1 ; 4 ; 3 ; 6] ;
%# Make a look-up table that tells us the relative order for each order id
sortmat(ordermat) = 1:length(ordermat);
%# Extract the order ID's from the big matrix
keys = bigmat(:,1);
%# Get the new ordering
new_key = sortmat(keys);
%# Sort the new ordering, remembering the permutation necessary
[~, permutation] = sort(new_key);
%# Apply the permutation to the big matrix
finalans = bigmat(permutation, :);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2201 次 |
最近记录: |