如何连接存储在结构中的多个Matlab表

时间:2015-10-12 19:39:20

标签: matlab dataset

我有一个存储在结构中的多个表。我想合并所有这些。行数不相同,但列数相同。公共密钥始终位于第一列。

对于两个表,很容易进行连接,但多个表有点棘手。我怎样才能做到这一点。

enter image description here

2 个答案:

答案 0 :(得分:0)

我能想到的最好的事情是轮询当前的工作区并查看当前存在的变量。然后,对于每个变量,如果它是一个结构,则将其连接到一个更大的结构上。当你完成后,你将拥有一个包含所有这些组合的大型结构。这需要使用whos,不幸的是eval

%// Larger structure initialization
largeStruct = [];

%// Get all variable names currently in workspace
vars = whos;

%// For each variable...
for ii = 1 : numel(vars)
    %// If this is a structure, and if the variable is not any of
    %// the current structure, the automatic variable answer and
    %// the current variable storing our variable names...
    if strcmpi(vars(ii).class, 'struct') && ~any(strcmpi(vars(ii).name, {'largeStruct', 'ans', 'vars'}))
        %// Concatenate to the larger structure
        largeStruct = eval(['[largeStruct ' vars(ii).name '];']);
    end
end

BTW,using eval is considered bad practice。由于您当前的工作空间状态,我不得不使用它。考虑使用存储所有这些嵌套结构的单个结构,其中字段是实际的变量名称本身......类似于stock.stockQuotes_070715, stock.stockQuotes_070815等。如果你这样做,我们就不必使用{ {1}}开头。

答案 1 :(得分:0)

我会轮询工作区,将所有数据集放在单元格数组中,使用cellfun转换为表格,然后使用递归外连接函数,如下所示:

tablecell = {Table1, Table2, Table3, ...}
tables = outerjoinmultiple(tablecell)


function table = outerjoinmultiple(tables)

if size(tables, 2) == 1
    table = tables{1};
else
    t2 = outerjoinmultiple(tables(2:end));
    table = outerjoin(tables{1}, t2, 'MergeKeys', true);
end