I want to add data to an array of structs without the fields of the added structs necessarily having the same order as the fields of the original structs. For example:
% Works fine:
students.name = 'John';
students.age = 28;
student2.name = 'Steve';
student2.age = 23;
students(2) = student2;
% Error if the order of the fields of student2 is reversed
students.name = 'John';
students.age = 28;
student2.age = 23;
student2.name = 'Steve';
students(2) = student2; % Error: Dissimilar structs
Is there a variant of struct I can add data to without having to keep the same order of fields?
EDIT: One workaround would be to always use matlabs "orderfields", which orders fields alphabetically. That is, the above erroneous example would become:
% Order fields alphabetically
students.name = 'John';
students.age = 28;
student2.age = 23;
student2.name = 'Steve';
students = orderfields(students);
student2 = orderfields(student2);
students(2) = student2; % Works
I am not sure whether this is the most natural solution.
A "natural" solution would be to initiallize (create) each struct with a fixed order of fields. Once the struct has been created this way, you can fill its fields in any order.
Also, you could encapsulate the creation in a function. This simplifies code and assures order is consistent. In your case, the creator function could be
create_student = @(x) struct('name',[], 'age',[]); %// empty fields. Fixed order
So your code would become
students = create_student(); %// call struct creator
students.name = 'John';
students.age = 28;
student2 = create_student(); %// call struct creator
student2.age = 23;
student2.name = 'Steve';
students(2) = student2; %// Now this works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With