2015-06-25 100 views
2

我有兩個表,比如價格(5行,1列)和定價(6行,1列),它們沒有任何共同之處。我想獲得完整的外部聯接,這樣我的新表ABC就有30行,基本上,定價中的每一行都有所有的價格。兩個表的全外連接

如何做到這一點?我可以使用全外連接還是其他的?

+0

這不是一個跨產品,而不是外連接?如果沒有共同之處,外連接不僅僅是11行,並且其他表列有'NULL'? – Dan

+0

是的。究竟!它就像我們的DBA人員說的兩個表格的「Cartisian Product」一樣。但是如何在Matlab中做到這一點? – JenZ

回答

0

我的回答涵蓋了兩種情況:

  1. P(價格)PD(pricedates)
  2. P(價格)PD(pricedates)陣列

下面是代碼:

% generate some sample data 
price  = [1;2;3;4;5]; 
pricedate1 = [11;12;13;14;15;16]; 
pricedate2 = pricedate1+10; 
pricedate3 = pricedate2+10; 

% create sample table 
P = table(price); 
PD = table(pricedate1,pricedate2,pricedate3); 

% this is the code if P and PD are tables 
TMP = repmat(P{:,1},1,size(PD,1))'; 
T = [repmat(PD,size(P,1),1),table(TMP(:),'VariableNames',{'price'})] 

% create sample arrays 
P = price; 
PD = [pricedate1,pricedate2,pricedate3]; 

% this is the code if P and PD are arrays 
TMP = repmat(P,1,size(PD,1))' 
T = [repmat(PD,size(P,1),1), TMP(:)] 

有可能將它寫在一個單線到消除TMP -variable。

對於table類型的數據:

T = [repmat(PD,size(P,1),1),table(subsref(repmat(P{:,1},1,size(PD,1))',struct('type','()','subs',{{':'}})),'VariableNames',{'price'})] 

對於array類型的數據:

T = [repmat(PD,size(P,1),1),subsref(repmat(P,1,size(PD,1))',struct('type','()','subs',{{':'}}))]; 

我承認,是單線看起來相當神祕。

+0

非常感謝。讓我仔細閱讀並且消化它。 – JenZ

+0

是的!這是答案! – JenZ

+0

但嘗試單行時出錯:T = [repmat(PD,size(P,1),1),table(subsref(repmat(P {:,1},1,size(PD,1 )'',struct('type','()','subs',{{':'}}),'VariableNames',{'price'})] 來自非單元陣列對象 – JenZ

0

因爲它看起來像你正在嘗試做一個笛卡爾積,我建議使用來自FileExchange的allcomb功能,http://www.mathworks.com/matlabcentral/fileexchange/10064-allcomb

,因爲你的數據也是(MATLAB)表(希望),你可以這樣做:

function Tallcomb = allcomb_2tables(T1, T2) 
    %USe allcomb to create the cartesian product of the indexes 
    idxAB = allcomb(1:height(T1),1:height(T2)); 

    % Now horzcat the multi-broadcasted tables: 
    Tallcomb = horzcat(T1(idxAB(:,1),:), T2(idxAB(:,2),:)); 

end 
+0

謝謝!我會嘗試。它看起來很有趣。 – JenZ