Arsenal Fanatic
Arsenal Fanatic

Reputation: 3803

Create Nested Structures with variable name same as value of a variable in Matlab?

I want to create a structure where in first level will have the variable names for eg:- a

>> a=struct()

a = 

struct with no fields.

>> for i=1:30
a.i=rand(3);
end
>> a

a = 

    i: [3x3 double]

a.i

ans =

    0.3477    0.2621    0.2428
    0.1500    0.0445    0.4424
    0.5861    0.7549    0.6878

But what I want to create is a structure where 'a' is a struct contains 30 fields where a.1 ; a.2 ;a.3; each give a random matrix which was previously assigned.

I would also like to do this same thing but for 'i' Strings and not just numbers. For example a video is read and some particular data from every frame is stored in a struct with the variable name of the frame number.

expected result

Upvotes: 0

Views: 139

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Your code just defines a field called i, 30 times.

You can build a different field name in each iteration using variable field names. Field names must begin with a letter, so you need to use something like f1, f2 etc. as names. To do it, you build the string representing the field name (in this case that string is ['f' num2str(i)]) and put parentheses around it:

for i = 1:30
    a.(['f' num2str(i)]) = rand(3);
end

This gives

a = 
     f1: [3x3 double]
     f2: [3x3 double]
     f3: [3x3 double]
     f4: [3x3 double]
          ...

Upvotes: 1

Related Questions