0

I would like to create a struct that is named after a dynamic variable. Something like:

for t = 1:2

    for b = 1:70
        Father.t.b.A = A;
        Father.t.b.C = C;
    end
end

and when looking at Father there is Father.1.1.A, Father.1.2.A, ... , Father.2.70.C.

Thanks for any help.

Suever
  • 64,497
  • 14
  • 82
  • 101
Maguzi
  • 23
  • 5
  • 4
    Variable names, including structure field names, [cannot start with a number](http://www.mathworks.com/help/matlab/matlab_prog/variable-names.html). Use an array of structures: `Father(t, b).A = A`; – sco1 Aug 14 '16 at 17:05
  • You should definitely do as @excaza has shown rather than the answer below as it is much cleaner and easier to read and understand. – Suever Aug 14 '16 at 18:38
  • @Suever is right, it's not a good practice to use my answer, I just wanted to show you the syntax. – Rotem Aug 14 '16 at 18:44
  • @Rotem it is good practice to use dynamic field names, it's just not at all applicable to the question. – sco1 Aug 14 '16 at 19:33

2 Answers2

2

MATLAB allows for arrays of structures that can be indexed similarly to its other arrays:

for t = 1:2
    for b = 1:70
        Father(t, b).A = A;
        Father(t, b).C = C;
    end
end
sco1
  • 12,154
  • 5
  • 26
  • 48
0

You can use the following sample to create the struct (like excaza mentioned, field names starting with a number are not allowed):

A = 1;
C = 3;

for b = 1:7
    Father.(['b', num2str(b)]) = struct('A', A, 'C', C);
end

Now:

Father.b1.A equals 1
Father.b5.C equals 3

Rotem
  • 30,366
  • 4
  • 32
  • 65