image thumbnail

catStructs.c

version 1.0.0.0 (2.13 KB) by Christopher Harris
catStructs.c concatinates two structures, each with unique feilds. Outputs one structure.

76 Downloads

Updated 25 Jan 2015

View License

I found myself in the situation of needing to concatenate two structures together and it seems that Matlab does not have a very clean method of accomplishing this. In fact, I think the next best thing to do is something like:
>> a(1).a = [1 2 3];a(2).a = [2 3 4]; a(1).b = 'hello';a(2).b = 'again';
>> b(1).c = {1 2 3 4};b(2).c = {3 4 5 6};
>> x = b;
>> names = fieldnames(a);
>> for i=1:numel(names);for j=1:numel(a);x(j).(names{i}) = a(j).(names{i});end;end
>> x

x =

1x2 struct array with fields:

c
a
b
>> x(1)

ans =

c: {[1] [2] [3] [4]}
a: [1 2 3]
b: 'hello'

Which I hate to do (not to mention it looks dumb and clunky).

After a while, I decided to just make another silly function to accomplish this silly task. It takes two structures (should have the same number of dimensions!!) and outputs the concatenation of the two. The two inputs should have unique field names (as in the example above) and each field across each dimension should be similar (ie. a(1).a and a(2).a are both numerical arrays).

Example :

>> xx = catStructs(a,b)
xx =
1x2 struct array with fields:

a
b
c

>> a(1).a = [1 2 3];a(2).a = [2 3 4]; a(1).b = 'hello';a(2).b = 'again';
>> b(1).c = {1 2 3 4};b(2).c = {3 4 5 6};
>> xx(1)
ans =
a: [1 2 3]
b: 'hello'
c: {[1] [2] [3] [4]}

Unfortunately, it is a bit slower that the forloop method when the array sizes become very large. I have not optimized the code yet. I created it merely for code tidiness.

Cite As

Christopher Harris (2021). catStructs.c (https://www.mathworks.com/matlabcentral/fileexchange/49158-catstructs-c), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2013a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!