Q_1.0
Q_1.0

Reputation: 183

Add more fieldnames to an existing struct

If I have a struct, handles,

handles = struct('a',1,'b',2,'c',3)

I also have a cell of strings and a cell of numbers

cell1 = {'d','e','f'};
cell2 = {4,5,6};

How do I add the field names from cell1 to handles with values from cell2?

Upvotes: 3

Views: 75

Answers (1)

sco1
sco1

Reputation: 12214

Though there is likely a more efficient method, the first thing that comes to mind would be utilizing dynamic field names:

handles = struct('a',1,'b',2,'c',3);

cell1 = {'d','e','f'};
cell2 = {4,5,6};

for ii = 1:length(cell1)
    handles.(cell1{ii}) = cell2{ii};
end  

Which returns:

handles = 

    a: 1
    b: 2
    c: 3
    d: 4
    e: 5
    f: 6

Upvotes: 3

Related Questions