【问题标题】:MATLAB: Merging / combining struct [duplicate]MATLAB:合并/组合结构
【发布时间】:2018-03-19 18:51:27
【问题描述】:

快速的问题让我费了些力气才巧妙地解决了……

采用两个具有唯一字段的结构。

% Struct #1
S_1.a = 1;
S_1.b = 2;
S_1.c = 3;

% Struct #2
S_2.d = 1;
S_2.e = 2;

如何将它们合并成一个包含所有两个结构的结构?

根据 AFAIK,MATLAB 没有自动组合结构的命令。

手动输入的显而易见的方法:S_1.d = S_2.d; 当然是令人沮丧的,也是对时间的低效利用。

【问题讨论】:

  • 在搜索“MATLAB combine struct”或类似内容时不会出现建议的副本。只能通过在搜索词中输入“结构”来找到重复项,因此对于在 matlab 中查找组合结构的人来说它不是很有用(就像我在一起解决解决方案之前所做的那样)。我建议要么编辑另一篇文章,希望能给它搜索相关性,要么留下重复标记,让读者了解这两个问题。
  • FWIW,这是matlab combine structure site:stackoverflow.com 的第一个 Google 结果。但是,是的,这就是将问题标记为重复问题的意义所在。

标签: matlab struct


【解决方案1】:

一种解决方案是循环遍历fieldnames

% Combine  into a single output structure
f = fieldnames(S_2);
for i = 1:size(f,1)
    S_1.(f{i}) = S_2.(f{i});
end

这种方法的一个缺点是同名的字段会在没有警告的情况下被覆盖。这可以通过 strcmp 进行标记。因此,一个更慢但更健壮的函数是:

function S_out = combineStructs(S_1,S_2)
%  Combines structures "S_1","S_2" into single struct "S_out"
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Get fieldnames
f_1 = fieldnames(S_1);
f_2 = fieldnames(S_2);

%Check for clashes
for i = 1:size(f_1,1)
    f_i = f_1{i};
    if max(strcmp(f_i,f_2)) %strcmp returns logic array.
        %Pop-up msg; programme continues after clicking
        errordlg({'The following field is repeated in both structs:';'';...
            f_i;'';...
            'To avoid unintentional overwrite of this field, the program will now exit with error'},...
            'Inputs Invalid!')
        %Exit message; forces quit from programme gives a pop-up
        error('Exit due to repeated field in structure')
    end
end

% Combine  into a single output structure
for i = 1:size(f_1,1)
    S_out.(f_1{i}) = S_1.(f_1{i});
end
for i = 1:size(f_2,1)
    S_out.(f_2{i}) = S_2.(f_2{i});
end

end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多