Zanam
Zanam

Reputation: 4807

Matlab: structures with variable name as index

I am not sure this is possible in Matlab but wanted to make sure.

I have structures as:

x = struct();
x.val1 = 5;
x.val2 = 7;

y = struct();
y.val1 = 15;
y.val2 = 17;

I want to create a structure DataStore as:

DataStore = struct;
DataStore(x).val1 = 5
DataStore(x).val2 = 7
DataStore(y).val1 = 15
DataStore(y).val2 = 17

OR

DataStore = struct;
DataStore('x').val1 = 5
DataStore('x').val2 = 7
DataStore('y').val1 = 15
DataStore('y').val2 = 17

So, I am using the name of the original structure variables as index for DataStore.

Is the above feasible ?

Edit:

I aim to use DataStore as following:

disp( DataStore('x').val1 )
disp( DataStore('y').val2 )

Upvotes: 0

Views: 284

Answers (1)

Daniel
Daniel

Reputation: 36710

Use a struct, maybe with dynamic field names.

Either:

DataStore.x.val1=6
DataStore.x.val2=9

Alternative with dynamic filed names (result is the same):

f='x'
DataStore.(f).val1=6
DataStore.(f).val2=9

In case val1 and val2 are not just placeholders, concider replacing them with an array:

DataStore.(f).val(1)=6
DataStore.(f).val(2)=9

Upvotes: 4

Related Questions