MATLAB: How to concatenate two structures of different size

shadow function namesshadow inbuiltstructures concatenate

Hi to all I have something like this
function res=newRessource (size)
for k=1: size
res.a(k).v1= val1;
res.a(k).v2= val2;
end
then i have
res1= newRessource (size1);
res2= newRessource (size2);
After that in a for loop the content of the attributes of res1 are changed at each iteration and its size also and What i want to do, at the end of each iteration of the for loop, is to get the old content of res2 concatenated with the content of res1 because i will need to do some actions based on it later
I tried
res2 = [res2, res1];
but i get an error "Error using Horizcat Number of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of fields."
Any help on how to solve this? Thanks

Best Answer

You are changing the set of fields.
The below will merge the two by creating the missing fields.
res1fields = fieldnames(res1);
res2fields = fieldnames(res2);
%add fields that are in res2 but not in res1
res1copy = res1;
for K = 1 : length(res2fields)
thisfield = res2fields{K};
if ~ismember(thisfield, res1fields)
res1copy(1).(thisfield) = []; %create the field, make it empty

end
end
%add fields that are in res1 but not in res2
res2copy = res2;
for K = 1 : length(res1fields)
thisfield = res1fields{K};
if ~ismember(thisfield, res2fields)
res2copy(1).(thisfield) = []; %create the field, make it empty
end
end
%now do the appending
res2 = [res2copy, res1copy];