1

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

Suever
  • 64,497
  • 14
  • 82
  • 101
rafalio
  • 3,928
  • 4
  • 30
  • 33

3 Answers3

8

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.

Andrew Janke
  • 23,508
  • 5
  • 56
  • 85
  • Hey, thanks for this! How about if I want to have an array of structs for 'kids' ? I'm trying to simulate a binary tree, so a node has a label, and two subtrees, left and right. – rafalio Feb 01 '12 at 16:26
  • Just assign in to it, without `()` indexing. Something like `d.kids = [d d];`. Seriously, go read the "Getting Started" guide, and work the examples. It'll cover this, e.g. in section MATLAB > Getting Started > Programming > Other Data Structures > Structures. – Andrew Janke Feb 01 '12 at 16:40
  • if you're trying to create a binary tree, try this:http://www.mathworks.com/matlabcentral/fileexchange/12339-datastructures or you could roll your own using Matlab's classes (look up 'classdef') – Marc Feb 01 '12 at 16:42
1

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.

Clement J.
  • 3,012
  • 26
  • 29
1

You can also do it in a shorter way:

d.op = 1;
d.kids.op = 2;
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104