0

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 )
2
  • Are you looking for the concatenation of structs in MATLAB? Commented Mar 19, 2016 at 21:24
  • 2
    Why not just do Datastore.x.val1 = 5, etc.? Commented Mar 19, 2016 at 21:37

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Worth noting is that fields can be accessed using strings as well. disp( DataStore.('x').val1 ) or disp( DataStore(f).val1 ). It is kind of implied, but it might be worth being explicit with reading and writing. Still, +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.