How to put a struct in a struct

rafalio picture rafalio · Feb 1, 2012 · Viewed 9.6k times · Source

I just started using Matlab, and I absolutely despise (or not properly understand), the typesystem (or lack thereof).

Why does this not work ? I just want structs within structs (in a recursive function)

    K>> d = struct('op',1,'kids',[])

    d = 

          op: 1
        kids: []

    K>> d.kids(1) = struct('op',2)
    Conversion to double from struct is not possible.

I tried other things, like making d=struct('op',1,'kids', struct([])), but nothing seems to work....

Answer

Andrew Janke picture Andrew Janke · Feb 1, 2012

When you index into it with (1), you're trying to assign the struct in to the first element of d.kids, which is already a double array and thus a type mismatch. Just assign over the entire field.

d.kids = struct('op', 2);

To initialize it with a struct to start out with, do this, calling struct with no arguments instead of passing [] to it.

d = struct('op',1, 'kids',struct());

Don't give in to despair and hatred yet. The type system can handle what you want here; you're just making basic syntax mistakes. Have a read through the MATLAB Getting Started guide, especially the "Matrices and Arrays" and "Programming" sections, found in the online help (call doc() from within Matlab) or the MathWorks website.