两个表的完全外连接

时间:2015-06-25 14:21:58

标签: matlab outer-join

我有两张表,比如价格(5行,1列)和定价(6行,1列),它们没有任何共同之处。我想获得全外连接,这样我的新表ABC就有30行,基本上,每一行中的每一行都有价格。

怎么做?我可以使用全外连接或其他东西吗?

2 个答案:

答案 0 :(得分:0)

我的回答包括两个案例:

  1. P (价格)PD (定价)表格
  2. P (价格)PD (定价)数组
  3. 以下是代码:

    % 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 - 变量。

    对于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',{{':'}}))];
    

    我承认,单行显得非常神秘。

答案 1 :(得分: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
相关问题