This function is a must for people using structures. I wonder why MATLAB doesn't allow (as far as I know) structure concatenation using the [S1, S2] syntax, when the two structures have different fields. The builtin function STRUCT can't add fields to an existing structure...
16 Apr 2007
Nadaraja Pillai
Hi ,
It is possible to concates the structure simply using collon... For example...
X=[S1:S2:S3....]
It will do it...
04 May 2007
Jingzhao Ou
A very useful script!
21 Sep 2007
Jos (the author)
new version 2.0 (sep 2007). A bug was removed which ocured when fields contained cell arrays.
21 Feb 2008
Hoi Wong
Cool program. I can't imagine why MATLAB wouldn't have something like this built-in, but you filled the gap!
28 May 2008
Maziar Hashemi-Nezhad
Perfect basic program
Thanks
04 Aug 2008
Piotr .
Very useful function!
29 Sep 2008
Benny .
Good job. It would be very usefull if it also worked on general structures, not only those containing numerical matrices only, e.g.
a = dir('*.txt');
b = dir('*.mat');
c = catstruct(a,b);
29 Sep 2008
Jos (the author)
To Benny. Catstruct does work on structures with non-numeric fields (see the example). You're after simple concatenation, for which you do not need catstruct at all ...
Nice work, just one comment:
I just noticed that when merging two structures, the fact that any dissimilar fields in the FIRST level are merged, but dissimilarities in subsequent levels are lost: e.g.
gives s3.A = a : 101.
i.e. we lose field b. I kind of understand the logic, i.e. that it is now field A that is being overwritten by a new field A, so that a depth=1 merge has occurred, but for anyone looking to do a true merge-style operation, this means needing to loop though each level... any plans to change this?
This works well. I agree with Jeremy that recursive concatenation would be an advantage. It would also be useful to concatenate arrays and cells at the leaf nodes in the case when the fieldnames match (I've had to do this many times).
But it works for what I'm doing at the moment. Thanks!
I also needed to concatenate arrays and cells at the leaf nodes in the case when the fieldnames match. This can be done by slightly adjusting the code as:
if numel(UFN) ~= numel(FN),
warning('catstruct:DuplicatesFound','Duplicate fieldnames found. Fields are merged and sorted.') ;
Nd = numel(unique(j));
for i=1:Nd
idx = find(j==unique(j(i)));
[nr,nc] = cellfun(@size, VAL(idx));
% comment if fields are not required to be equal in size:
if diff(nr) || diff(nc);error(['Duplicate field ' FN{idx(1)} ' does not have the same size for all structures.']);end
[p,rcm] = min([nc(1) nr(1) 2]);
% concatenate rows as rows, colums as colomns and matrices along 2nd dimension.
VAL{idx(end)} = cat(min(rcm,2),VAL{idx});
end
sorted = 1;
end