Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

MatLab structures

  1. Aug 11, 2011 #1
    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?
     
  2. jcsd
  3. Aug 11, 2011 #2
    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 (Text):

    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: Aug 11, 2011
  4. Aug 12, 2011 #3
    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?
     
  5. Aug 12, 2011 #4
    Also, what if you wanted to add a new element at a later time. Say

    name: 'Mike'
    num_kids: 1
    kids_age: 3
     
  6. Aug 12, 2011 #5
    Code (Text):

    people(3) = struct('name', 'Mike', 'num_kids', 1, 'kids_age', 3);
     
     
  7. Aug 14, 2011 #6

    Pythagorean

    User Avatar
    Gold Member

    Fantastic Mr X, I've had issues with this in the past, nice workaround.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: MatLab structures
Loading...