Is there a variant of Matlab structures that does not provide field ordering?

I want to add data to an array of structures without fields of added structures that are necessarily in the same order as the fields of the original structures. 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 the structure into which I can add data without preserving the same field order?

EDIT: One workaround is to always use the "matlabs" attributes, which sort the fields alphabetically. That is, the above error example will be as follows:

 % 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 if this is the most natural solution.

+7
struct matlab
source share
3 answers

The β€œnatural” solution is to initialize (create) each structure with a fixed field order . When the structure is created in this way, you can fill in its fields in any order.

Alternatively, you can encapsulate the creation into a function . This simplifies the code and ensures that the order is consistent. In your case, the creator function may be

 create_student = @(x) struct('name',[], 'age',[]); %// empty fields. Fixed order 

So your code will 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 
+4
source share

Yes, there is an alternative that uses classes. See classdef documentation, for example, or, in general, the Matlab OOP start page . Please note that before using them, you need to write some class files, therefore it is not as simple as using structures, but it is more flexible after def class is executed.

+2
source share

A simple way is to apply orderfields before assigning any structure, as Daniel suggests in the comments

 >> students(1) = orderfields(struct('name', 'John', 'age', 18)); >> students(2) = orderfields(struct('age', 20, 'name', 'Jane')); 
+1
source share

All Articles