Question

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....

Was it helpful?

Solution

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.

OTHER TIPS

You don't need an index on your second command.

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

Your initial value [] don't make the field to be an array.

EDIT: Andrew's answer is clearer. I would add you can use the command class to ask Matlab about the type of an expression if you're unsure.

You can also do it in a shorter way:

d.op = 1;
d.kids.op = 2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top