Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

merge fields of two struct in one

1,093 views
Skip to first unread message

DF

unread,
Aug 23, 2011, 7:40:10 AM8/23/11
to
I have 2 struct variables, let's say s1 and s2, with exactly the same fields:
s1.name: 'alice'
s1.age: 22
s1.height: 175

s2.name: 'alex'
s2.age: 23
s2.height: 180

How can I combine the data in one structure, with the same fields to get something like this:

s3.name: ['alice' 'alex']
s3.age: [22 23]
s3.hieght: [175 180]

The struct variable has many fields and I don't want to do this merge manually field by field.

Bruno Luong

unread,
Aug 23, 2011, 8:25:09 AM8/23/11
to
s1.name='alice';
s1.age=22;
s1.height=175;
s1

s2.name='alex';
s2.age=23;
s2.height=180;
s2

fields = fieldnames(s1)';
fields(2,:) = cellfun(@(f) [s1.(f) s2.(f)], fields, 'unif', false);
smerge = struct(fields{:})

%%%%%%%%%%%
Note that

'>> ['alice' 'alex'] % as *you* require

ans =

alicealex

% Bruno

0 new messages