MATLAB:合并/组合结构

时间:2018-03-19 18:51:28

标签: matlab struct

快速的问题让我有点摆弄整齐地解决......

采用具有独特字段的两个结构。

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

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

如何将它们合并到包含所有两个结构的单个结构中?

MATLAB没有,AFAIK,有一个自动组合结构的命令。

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

1 个答案:

答案 0 :(得分:2)

一种解决方案是循环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