假设所有变量的类型都与大小(维度)struct相同.例如:fieldsconcatenatable
a.x = 1; a.y = 2;
b.x = 10; b.y = 20;
Run Code Online (Sandbox Code Playgroud)
与普通串联:
c = [a; b];
Run Code Online (Sandbox Code Playgroud)
回报
c(1).x = 1; c(1).y = 2;
c(2).x = 10; c(2).y = 20;
Run Code Online (Sandbox Code Playgroud)
我想要的是:
c.x(1) = 1; c.y(1) = 2;
c.x(2) = 10; c.y(2) = 20;
Run Code Online (Sandbox Code Playgroud)
它可以通过以下方式完成:
c.x = [a.x; b.x];
c.y = [a.y; b.y;];
Run Code Online (Sandbox Code Playgroud)
但是,如果变量有很多字段,
a.x1 = 1;
a.x2 = 2;
% Lots of fields here
a.x100 = 100;
Run Code Online (Sandbox Code Playgroud)
编写这样的代码是浪费时间.有什么好办法吗?
该函数执行您想要的操作,但没有错误检查:
function C = cat_struct(A, B)
C = struct();
for f = fieldnames(A)'
C.(f{1}) = [A.(f{1}); B.(f{1})];
end
Run Code Online (Sandbox Code Playgroud)
您可以在上面的代码中像这样使用它:
c = cat_struct(a, b);
Run Code Online (Sandbox Code Playgroud)