MATLAB: Concatenate same fields in multiple structures in a loop using field names

concatenatefieldsloopstructure

I have several .mat files and each is a structure with the same fields. For each field, I'd like to create an array that has the name of that field and is the concatenation of all structures with that field name. I can provide a psuedo-code, but not sure how to write it out for real:
firststruct has field names 'one' and 'two'
secondstruct has field names 'one' and 'two'
for i = 1:number of structure files I have (the .mat files)
get the field names
for j = 1:number of field names
'this would be the name of the first field (so 'one')' = this would create a vector that concatenates all .one fields;
'this would be the name of the second field (so 'two')' = this would create a vector that concatenates all .two fields;
end
end
To try to be clearer, if firststruct.one = [1,2] and secondstruct.one = [3,4], the result I'm hoping for is one = [1,2,3,4].

Best Answer

Because all of the structures contain the same fieldnames they should be stored as one non-scalar structure:
>> S(1).one = [1,2];
>> S(1).two = NaN;
>> S(2).one = [3,4];
>> S(2).two = Inf;
Then the concatenation can be done in just a few lines:
>> C = struct2cell(S);
>> C = cellfun(@(c)[c{:}],num2cell(C,2:3),'uni',0);
>> Z = cell2struct(C,fieldnames(S),1);
>> Z.one
ans =
1 2 3 4
>> Z.two
ans =
NaN Inf
EDIT: to load multiple mat files, where each contains one structure of unknown name:
for k = 1:numel(...)
F = ... filename
T = struct2cell(load(F));
S(k) = T{1};
end