Eli Ben Shimol
Eli Ben Shimol

Reputation: 23

How do I copy fields names and their contents to another struct variable in matlab

Lets say that I have this code:

a=struct;
a(1).a='a1';
a(1).b='b1';
a(1).c='c1';

a(2).d='a1';
a(2).e='b1';
a(2).f='c1';

a(3).g='a1';
a(3).h='b1';
a(3).i='c1';

Now, I want to copy only a(2) to b(1) with its all fields, but I don't know what fields are in a. for example:

b=struct;
b(1)=a(2);
b(2)=a(3);

(if I do that I get the error: 'Subscripted assignment between dissimilar structures.') How can I do that?

Upvotes: 2

Views: 1819

Answers (2)

scmg
scmg

Reputation: 1894

Don't declare b. Then use deal:

a=struct;
a(1).a='a1';
a(1).b='b1';
a(1).c='c1';

a(2).d='a1';
a(2).e='b1';
a(2).f='c1';

a(3).g='a1';
a(3).h='b1';
a(3).i='c1';

b(1) = deal(a(2));
b(2) = deal(a(3));

If you declare b before using deal, you will have to declare b as a struct with all fields which a has. In this case you don't need 'deal' anymore, just assign them normally as you did.

Upvotes: 1

Divakar
Divakar

Reputation: 221704

Let s1 be the input struct and s2 be the desired output struct. Here's one approach based on struct2cell and cell2struct to get s2 -

%// Given input struct
s1=struct;
s1(1).a='A';
s1(1).b='B';
s1(1).c='C';

s1(2).d='D';
s1(2).e='E';
s1(2).f='F';

s1(3).g='G';
s1(3).h='H';
s1(3).i='I';

idx = [2 3]; %// indices of struct data to be copied over from s1 to s2

fn = fieldnames(s1)   %// get fieldnames
s1c = struct2cell(s1) %// Convert s1 to its cell array equivalent

%// Row indices for the cell array that has non-empty cells for the given idx
valid_rowidx = ~all(cellfun('isempty',s1c(:,:,idx)),3)

%// Construct output struct
s2 = cell2struct(s1c(valid_rowidx,:,idx),fn(valid_rowidx))

Thus, you would end up with the output -

s2 = 
1x2 struct array with fields:
    d
    e
    f
    g
    h
    i

Finally, you can verify the contents of the output struct like so -

%// Verify results
check1 = [s1(2).d s1(2).e s1(2).f]
check2 = [s2(1).d s2(1).e s2(1).f]

check3 = [s1(3).g s1(3).h s1(3).i]
check4 = [s2(2).g s2(2).h s2(2).i]

which yields -

check1 =
DEF
check2 =
DEF
check3 =
GHI
check4 =
GHI

Upvotes: 3

Related Questions