Defining a Struct with Multiple Elements

  • Context: MATLAB 
  • Thread starter Thread starter Apteronotus
  • Start date Start date
  • Tags Tags
    Elements Multiple
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 3K views
Apteronotus
Messages
201
Reaction score
0
Hi

The following structure has 2 elements.

people = struct(...
'name',{'bob', 'john'},...
'numKids',{0, 2}, ...
'kidsage',{[],[12,9]});

each element people(1), people(2) has three frields (name, numKids, kidsage)

Instead of declaring the structure in one line as above, I would like to define it one field at a time.
The closest working example I've been able to come up with is

people = struct

people.('name') = {'bob, 'john'}
people.('numkids') = {0, 2}
people.('kidsage') = {[], [12, 9]}

But defined in this way, the people structure only has one element.
ie.
people(1) =

name: {'bob' 'john'}
numkids: {[0] [2]}
kidsage: {[] [12, 9]}

Can anyone help?
 
Physics news on Phys.org
Although the documentation might lead one to believe this functionality exists, (from the text under the heading "Specifying Cell Versus Noncell Values"), it does not seem to exist, at least with version R2009a.

Instead, one may create a cell array and then convert it to a structure.

Code:
people_cell_array = cell(2, 3);

people_cell_array(:, 1) = {'bob' ; 'john'};
people_cell_array(:, 2) = {0 ; 2};
people_cell_array(:, 3) = {[] ; [12, 9]};

people = cell2struct(people_cell_array, {'name', 'num_kids', 'kids_age'}, 2);
 
Last edited:
MisterX
Thank you. Your code definitely produces the results that I was looking for.
Do you have any idea why my original code didnt work?
 
Also, what if you wanted to add a new element at a later time. Say

name: 'Mike'
num_kids: 1
kids_age: 3
 
Code:
people(3) = struct('name', 'Mike', 'num_kids', 1, 'kids_age', 3);