Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating two or more struct-type variables in MATLAB

Tags:

matlab

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?

like image 778
Jeon Avatar asked Oct 20 '22 12:10

Jeon


1 Answers

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);
like image 58
user664303 Avatar answered Oct 30 '22 13:10

user664303