MATLAB Defining a Struct with Multiple Elements

  • Thread starter Thread starter Apteronotus
  • Start date Start date
  • Tags Tags
    Elements Multiple
AI Thread Summary
The discussion revolves around creating a structure in MATLAB with multiple elements, specifically defining it one field at a time. The initial attempt to create a structure with two elements using a single line of code resulted in a structure with only one element. The user sought a method to define the structure incrementally. A successful solution was presented, involving the creation of a cell array that is then converted to a structure using the `cell2struct` function. This approach allows for the proper definition of multiple elements within the structure. Additionally, the conversation touched on the ability to add new elements to the structure later, demonstrating flexibility in managing the data. The workaround provided was appreciated for its effectiveness in addressing the user's needs.
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);
 
Fantastic Mr X, I've had issues with this in the past, nice workaround.
 
Back
Top