2016-04-25 55 views
0

我有两个表(或实际上我有几个),应该合并使用innerjoin。它按预期工作;除了它在“Keys”上排序,它会销毁我的数据,因为它实际上必须按原始行顺序排列。合并表没有按键排序

从帮助部分:

C由值的关键变量

t1 = Case Val 
3 1 
1 1 
2 1 

t2 = Val2 Case Subset 
2 2 2 
1 2 2 
2 3 1 

tnew = innerjoin(t1,t2) 

tnew = Case Val Val2 Subset 
2 ... 
% will start with "2" since its a lower value than "3", but in t1 "3" was in lower row than "2", it is rearranged 

整理我应该如何避免排序?绝望地使用innerjoin

回答

1

除结果表外,innerjoin还返回两个额外的输出:第一个表的行索引和第二个表的行索引对应于输出中的行。

您可以简单地使用第二个输出来确定已使用的t1中的行,并且可以对这些行进行排序。然后使用排序顺序来更改连接结果中的行的顺序。

%// Setup the data 
t1 = table([3;1;2], [1;1;1], 'VariableNames', {'Case', 'Val'}); 
t2 = table([2;1;2],[2;2;3],[2;2;1], 'VariableNames', {'Val2', 'Case', 'Subset'}); 


%// Perform the inner join and keep track of where the rows were in t1 
[tnew, rows_in_t1] = innerjoin(t1, t2); 

%// Sort them in order to maintain the order in t1 
[~, sortinds] = sort(rows_in_t1); 

%// Apply this sort order to the new table 
tnew = tnew(sortinds,:); 

%// Case Val Val2 Subset 
%// ____ ___ ____ ______ 
%// 3  1  2  1  
%// 2  1  2  2  
%// 2  1  1  2 
+0

谢谢你,这工作完美! – Erik