Assuming types of all variables are struct
and have same fields
with concatenatable
size (dimensions). For example:
a.x = 1; a.y = 2;
b.x = 10; b.y = 20;
With the ordinary concatenation:
c = [a; b];
returns
c(1).x = 1; c(1).y = 2;
c(2).x = 10; c(2).y = 20;
What I want is:
c.x(1) = 1; c.y(1) = 2;
c.x(2) = 10; c.y(2) = 20;
It can be done by:
c.x = [a.x; b.x];
c.y = [a.y; b.y;];
However, if the variables have lots of fields,
a.x1 = 1;
a.x2 = 2;
% Lots of fields here
a.x100 = 100;
It's a waste of time to write such a code. Is there any good way to do this?
This function does what you want, but has no error checking:
function C = cat_struct(A, B)
C = struct();
for f = fieldnames(A)'
C.(f{1}) = [A.(f{1}); B.(f{1})];
end
You would use it like this in your code above:
c = cat_struct(a, b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With