0

I a bunch of data structures with an id (id1, id2, id3, ... idN) a single data field that contains variables (var1,var2,var3, ... varK), such that the first structure looks like

id1.data.variable1 = []
id1.data.variable2 = []
.
.
.

All id's share the same data and variable structure.

Now, I would very much like to append a new variable (newvar) to these existing structures in a loop.

For one structure, I would just do this:

id1.data.newvar1 = id1.data.var1^2 

which would add newvar1 to my id1.data with id1.data.var1^2 as values.

If i try

for i = 1:length(id_list)
      id_list{i}.data.newvar = id_list{i}.data.var1^2
end

I get a "Struct contents reference from a non-struct array object." error.

Any input is appreciated.

1
  • you are referencing id_list{i} as if it were a cell array. The error is because you try to reference the contents of that cell array as if it were a structure. What exactly is id_list? You might want to try (id_list{i}) if id_list is the list of all field names. Commented Sep 29, 2016 at 11:39

1 Answer 1

2

You can create a new global struct that contains the set of structs that you are working with. Thus, the new struct will have the following fields:

ID.id1, ID.id2, ..., ID.idnumber_of_ids

So, in order to loop each id#:

for i = 1:number_of_ids
    name = ['id' num2str(i)];
    ID.(name).data.newvar = ID.(name).data.var1^2;
end

Finally, save the struct without the ID high-level:

save('here.mat','-struct','ID');
Sign up to request clarification or add additional context in comments.

Comments

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.