我有一个已分类的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 ; ] ;
ordermat
中的所有ID(此处为整数)可能不会出现在bigmat中。如上所示id = 6
可以忽略它们。谢谢!
答案 0 :(得分:2)
这是我的解决方案:
ordermat = [2; 1; 4; 3; 6];
bigmat = [
1 10
1 30
1 40
2 1
2 11
3 58
4 2
4 5
];
%#bigmat = sortrows(bigmat,1);
%# keep valid IDs,
ord = ordermat( ismember(ordermat,bigmat(:,1)) );
ord = grp2idx(ord);
%# starting/ending locations of the different IDs in bigmat
startInd = find( diff([0;bigmat(:,1)]) );
endInd = [startInd(2:end)-1; size(bigmat,1)];
%# generate startInd(i):endInd(i) intervals
ind = arrayfun(@colon, startInd, endInd, 'UniformOutput',false);
%# order then combine the intervals of indices
ind = [ind{ord}];
%# get final sorted result
finalans = bigmat(ind,:);
我确保它处理不同的情况,例如:
ordermat
包含bigmat
中未找到的ID:ordermat = [2;1;4;3;6]
bigmat
的ID都在ordermat
中表示:ordermat = [2;1]
ordermat=ordermat+10; bigmat=bigmat+10;
答案 1 :(得分:1)
%# 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, :);
答案 2 :(得分:0)
我根据唯一标识符将bigmat
拆分为块,然后重新排序块,如下所示:
%# this assumes bigmat is sorted, btw
%# i.e. that the different ids are grouped together
%# find unique ids
dd = [true;diff(bigmat(:,1))~=0];
uniqueIDs = bigmat(dd,1);
%# reorder uniqueIDs
[~,newOrder] = ismember(uniqueIDs,ordermat);
%# if there are uniqueIDs that are not in ordermat
%# we'd need to remove those. I assume this won't
%# be the case
%# chop up bigmat
numUniqueIds = diff([find(dd);length(dd)+1]);
bigChunks = mat2cell(bigmat,numUniqueIds,size(bigmat,2));
%# reorder chunks
finalans = cat(1,bigChunks{newOrder});