Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a variant of Matlab structs that does not enforce the order of the fields?

Tags:

struct

matlab

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.

like image 794
jolo Avatar asked Nov 26 '14 14:11

jolo


1 Answers

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
like image 77
Luis Mendo Avatar answered Oct 06 '22 14:10

Luis Mendo